cplusplus初始化顺序

1,继承的顺序;

#include<iostream>

using namespace std;

class  AAA
{
    public:
    AAA(){
        cout<<"AAA"<<endl;
    }
};

class BBB
{
    public:
    BBB(){
        cout<<"BBB"<<endl;
    }
};

class CCC: public BBB , AAA
{
    public:
    CCC(){
        cout<<"cccc"<<endl;
    }
};


int main()
{
    CCC c1;

    return 0 ;

}

输出结果:

./a.out
BBB
AAA
cccc 

2,声明顺序:

#include<iostream>

using namespace std;

class  AAA
{
    public:
    AAA(){
        cout<<"AAA"<<endl;
    }
};

class BBB
{
    public:
    BBB(){
        cout<<"BBB"<<endl;
    }
};

class CCC
{
    public:
    CCC():a1(),b1(){
        cout<<"cccc"<<endl;
    }

    BBB b1;
    AAA a1;
    
};


int main()
{
    CCC c1;

    return 0 ;

}

输出结果:

./a.out
BBB
AAA
cccc

3,初始化列表的作用:

  • 常量成员, 因为常量只能初始化不能赋值, 所以必须放在初始化列表里面.

  • 引用类型, 引用必须在定义的时候初始化, 并且不能重新赋值, 所以也要写在初始化列表里面.

  • 没有默认构造函数的类类型, 因为使用初始化列表可以不必调用“缺省构造函数+拷贝赋值运算符”来初始化, 而是直接调用“拷贝构造函数”初始化.

    扫描二维码关注公众号,回复: 13084323 查看本文章

参考:

https://www.cnblogs.com/silenzio/p/11766609.html

猜你喜欢

转载自blog.csdn.net/zgb40302/article/details/115365828