C++小结

来源:互联网 发布:注册给排水知乎 编辑:程序博客网 时间:2024/05/21 20:29

指针:

数组名就是一个指针:

如:int a[3]={3,2,1}

int *p=a;

p[2]就为1

 

int b=3;

int* p=&b;

*p的值就为3

 

静态数据成员没有进入程序的全局名字空间,因此不存在同全局名字冲突问题

使用静态成员可以隐藏信息,因为静态变量可以是private的.

 

class test
{
public:
    static int i;
    int j;
    test(int a):j(a){}
    void fun1();
    static void func2();
};
int test::i=1//为了非静态变量区别,必须在外面初始化
void test::fun1(){cout<<i<<","<<j<<endl;}
void test::func2(){cout<<i<</*","<<j<<*/endl;}
//静态成员函数和静态变量一样,不属类的对象,不含this指针,无法调用类的非静态成员

 

//显式的调用构造函数

Class test
{
 public:
       test();
       test(char *name,int len=0){}
       test(char *name){}
};

当调用Test obj("Hello")时发生编译错误,由于构造函数的模糊广义,不知选择那个构造2or3,其实第三个函数没有存在必要。第二个已包括。

 

class test1
{
public:
    test1(int n){num=n;}
private:
    int num;
};
class test2
{
public:
    explicit test2(int n){num=n;}
private:
    int num;
};



int main()
{
    test1 t1=12;
    test2 t2(1);
    return 0;

}

构造函数再调用构造函数不会形成死循环,而是栈溢出,原因构造函数只是在栈上生成了一个临时对象,对于其毫无影响。