C++的构造和析构顺序

版权声明:http://blog.csdn.net/robertkun https://blog.csdn.net/robertkun/article/details/79202490

子类的构造和析构过程, 上代码:

#include <iostream>

using namespace std;

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

class CB : public CA {
public:
    CB() { cout << "CB()" << endl; }
    ~CB() { cout << "~CB()" << endl; }
};

int main() {
    cout << "Hello, World!" << endl;
    CB b;

    return 0;
}

输出:

Hello, World!
CA()
CB()
~CB()
~CA()

总结:

子类构造顺序:父类构造->子类有构造
子类析构顺序:子类析构->父类析构

孙子类的构造和析构过程, 上代码:

#include <iostream>

using namespace std;

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

class CB : public CA {
public:
    CB() { cout << "CB()" << endl; }
    ~CB() { cout << "~CB()" << endl; }
};

class CC : public CB {
public:
    CC() { cout << "CC()" << endl; }
    ~CC() { cout << "~CC()" << endl; }
};

int main() {
    cout << "Hello, World!" << endl;
    //CB b;
    CC c;

    return 0;
}

输出:

Hello, World!
CA()
CB()
CC()
~CC()
~CB()
~CA()

总结:

孙子类的构造过程: 爷类构造->父类构造-孙子类构造
孙子类的析构过程: 孙子类析构->父类析构->爷类析构

阅读更多

没有更多推荐了,返回首页