C++类的构造和析构顺序

#include <bits/stdc++.h>

using namespace std;

class B
{
public:
    B():_b(2) { cout << "B "; }
    B(int b) :_b(b) { cout << "B2 "; }
    int _b;
    ~B() { cout << " ~B "; }
};

class C
{
public:
    C():_c(3) { cout << "C "; }
    C(int c) :_c(c) { cout << "C2 "; }
    int _c;
    ~C() { cout << " ~C "; }
};

class Base1
{
public:
    Base1() :_base1(100) { cout << "Base1 "; }

    int _base1;
    B _Base1_Bclass;
    C _Base1_CClass;
    ~Base1() { cout << " ~Base1 "; }
};

class Base2
{
public:
    Base2() :_base2(100) { cout << "Base2 "; }

    int _base2;
    B _Base2_Bclass;
    C _Base2_CClass;
    ~Base2() { cout << " ~Base2 "; }
};

class A :
    public Base1, Base2
{
public:
    A() :_a(1), _CClass(C(3)) { cout << "A "; }
    int _a;
    B _bClass;
    C _CClass;
    ~A() { cout << " ~A "; }
};

int main() {
    A aClass;
    cout << endl;
}

运行结果是:

B C Base1  B C Base2   B C2 A
~A ~C ~B ~Base2  ~C ~B ~Base1  ~C ~B

构造过程:
1)先调用父类的构造函数(按继承顺序); 2)调用类成员对象的构造函数(按声明顺序,初始化列表不影响成员数据的构造顺序);3)调用本类的构造函数
析构过程和构造过程相反

C++类的构造和析构顺序

上一篇:ubuntu20.04设置动态ip,静态Ip


下一篇:Windows上帝模式