欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++在多继承时构造函数调用的顺序

程序员文章站 2022-03-03 08:52:11
...
今天看书时注意到C++在多继承时,基类的构造顺序是按照继承时给定顺序执行的,析构的顺序正好相反!而与它们初始化的顺序没有任何关系,下面随便写了一个Demo程序来验证C++在多继承时基类的构造顺序。



#include <iostream>
#include <cstdlib>

using namespace std;

class a
{
public:
a(){cout<<"a constructor!!"<<endl;}
~a(){cout<<"a deconstructor!!"<<endl;}
};

class b
{
public:
b(){cout<<"b constructor!!"<<endl;}
~b(){cout<<"b deconstructor!!"<<endl;}
};

class c
{
public:
c(){cout<<"c constructor!!"<<endl;}
~c(){cout<<"c deconstructor!!"<<endl;}
};

class d
{
public:
d(){cout<<"d constructor!!"<<endl;}
~d(){cout<<"d deconstructor!!"<<endl;}
};

class e
{
public:
e(){cout<<"e constructor!!"<<endl;}
~e(){cout<<"e deconstructor!!"<<endl;}
};

class f:public e,public b,public c,public d,public a
{
public:
f(){cout<<"f constructor!!"<<endl;}
~f(){cout<<"f deconstructor!!"<<endl;}
};


int main(int argc,char * args[])
{
f testObj;

system("pause");
return EXIT_SUCCESS;
}





类f分别继承自类e,类b,类c,类d和类a,在main函数中定义了一个testObj对象,这个对象的构造顺序是e->b->c->d->a,析构顺序正好相反。


程序运行结果如下图所示
[img]pic.JPG[/img]
相关标签: c++ demo