c++面试知识点

static

#include<stdio.h>
#include<iostream>
#include<assert.h>
using namespace std;

static int a=100;

void func()
{
    static int a=10;
    a++;
    cout<<a<<endl;
}
int main()
{
    for(int i=0; i<10; i++)
        func();

    a++;
    cout<<a<<endl;
}

#include<stdio.h>
#include<iostream>
#include<assert.h>
using namespace std;

static int a=100;

void func()
{
    a++;
}
int main()
{
  func(); a
++; cout<<a<<endl; }

#include<iostream>
using namespace std;

class A
{
public:
    A(){ updateCount(); }
    static int showCount;

    void updateCount(){ showCount++;}
    static void printCount(){ cout<<showCount<<endl; }
private:

};

int A::showCount=0;

int main()
{
    A::printCount();
    A a1;
    A a2;
    A::printCount();
}

联合:

联合(union)介绍
#include<stdio.h> #include<iostream> #include<assert.h> using namespace std; union test{ int a; char b; short c; }; int main() { test t; t.a=10; t.c=20; cout<<t.a<<endl; cout<<t.c<<endl; cout<<sizeof(test)<<endl; }

 

const

只读的

register

寄存器变量,要求编译器把一个变量的值保存在CPU寄存器而不是内存中,使对寄存器变量的操作比普通内存变量快。

注意:只能用register修饰局部变量和形式参数;在C中不能通过&运算符取寄存器变量地址,在C++取寄存器变量地址可能阻止它被优化。


extern

extern可以置于变量或者函数前,以标示变量或者函数的定义在别的文件中提示编译器遇到此变量和函数时在其他模块中寻找其定义

mutable

在C++中,mutable是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中,甚至结构体变量或者类对象为const,其mutable成员也可以被修改。

struct  ST

{

  int a;

  mutable int b;

};

const ST st={1,2};

st.a=11;//编译错误

st.b=22;//允许

volatile

volatile修饰的数据,"直接存取原始内存地址",编译器不可对其进行执行期寄存于寄存器的优化。这种特性,是为了满足多线程同步、中断、硬件编程等特殊需要。遇到这个关键字声明的变量,编译器对访问该变量的代码就不再进行优化,从而可以提供对特殊地址的直接访问。

一般说来,volatile用在如下的几个地方:

     1、中断服务程序中修改的供其它程序检测的变量需要加volatile;

     2、多任务环境下各任务间共享的标志应该加volatile;

     3、存储器映射的硬件寄存器通常也要加volatile说明,因为每次对它的读写都可能有不同意义

一个由C/C++编译的程序占用的内存分为以下几个部分。

  1. 栈区(stack):由编译器自动分配释放 ,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构中的栈。
  2. 堆区(heap):由程序员分配释放, 若程序员不释放,程序结束时可能由操作系统回收 。注意它与数据结构中的堆是两回事,分配方式倒是类似于链表。
  3. 全局/静态区(static): 全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态变量在一块区域,未初始化的全局变量和未初始化的静态变量在相邻的另一块区域。程序结束后由系统释放。
  4. 文字常量区:常量字符串就是放在这里的,程序结束后由系统释放。
  5. 程序代码区:存放函数体的二进制代码。
    int a = 0;// 全局初始化区 

  char *p1;//全局未初始化区 

  void main() 

  { 

    int b; //栈 

    char s[] = "abc"; //栈,运行时赋值

    char *p2;// 栈 

    char *p3 = "123456";// 123456在常量区,p3在栈上。编译时确定。 

    static int c =0;// 全局(静态)初始化区 

    p1 = (char *)malloc(10); //p1指向堆区,p1在栈上

} 

指针辨认;

int  * p;//指向int型的指针

void  * p;//空类型指针

int *  arr[10];//指针数组x存放10个指向int型的指针

int**  pp;//指针的指针(指向int型的指针的指针)

int  (*func_p)(int,int);//函数指针

注:在C中可以直接将void*指针赋值给其他任意类型指针,而在C++中需使用强制类型转换。

利用指针传递内存

void getMemory1(char *p)
{
    p=(char *)malloc(100);        //p为局部变量
}


char * getMemory2()
{
    char ch[]="hello world";    //在栈上分配内存,函数结束回收内存,ch将成为野指针
    return ch;
}


void  getMemory3(char **p)
{
    *p=(char*)malloc(100);        //正确
}

char * getMemory4()
{
    char *p;
    p=(char*)malloc(100);        //正确
    return p;
}

extern可以置于变量或者函数前,以标示变量或者函数的定义在别的文件中提示编译器遇到此变量和函数时在其他模块中寻找其定义

原文地址:https://www.cnblogs.com/huangcongcong/p/4006102.html