知识点讲解

构造函数

基类构造函数,对象成员构造函数,派生类自身构造函数

  • 多个基类时,按继承顺序
  • 多个对象成员时,按成员前后顺序

析构函数

派生类自身的析构函数,对象成员析构函数,基类析构函数

  • 多个基类时,与构造时相反
  • 多个对象成员时,与构造时相反

对象成员的调用顺序只跟声明顺序有关,跟初始化列表没有关系

示例代码

#include<iostream>
using namespace std;
 
class A
{
public:
        A() {cout << "A constructor called" << endl;}
        ~A(){ cout << "A destuctor called" << endl; }
};
 
class B
{
public:
        B(){ cout << "B constructor called" << endl; }
        ~B(){ cout << "B destructor called" << endl; }
};
 
class C: public B
{
public:
        C(){ cout << "C constructor called" << endl; }
        ~C(){ cout << "C destructor called" << endl; }
 
private:
        A a1;
        B b1;
};
 
int main()
{
        C c;
    cout << "------------------------------\n";
    return 0;
}


运行结果

B constructor called
A constructor called
B constructor called
C constructor called
------------------------------
C destructor called
B destructor called
A destuctor called
B destructor called

最后修改:2021 年 05 月 29 日 02 : 36 PM
如果觉得我的文章对你有用,请随意赞赏