C++一道题 跪求解答

2025-01-02 08:35:22
推荐回答(2个)
回答1:

#include "iostream"
using namespace std;
class Base1
{
public:
Base1(int x){cout<<"Base1 constructor called "< ~Base1(){cout<<"Base1 destructor called"<};

class Base2
{
public:
Base2(int x){cout<<"Base2 constructor called "< ~Base2(){cout<<"Base2 destructor called"<};

class Base3
{
public:
Base3(int x){cout<<"Base3 constructor called "< ~Base3(){cout<<"Base3 destructor called"<};

class Derived:public Base2,public Base1,public Base3 //这里决定顺序
{
private:
Base3 b3;//这里
Base1 b1;//决定
Base2 b2;//顺序

public:
Derived(int a,int b,int c,int d,int e,int f,int g):Base1(b),Base2(c),Base3(d),b1(e),b2(f),b3(g)
{
cout<<"Derived constructor called "< }
~Derived(){cout<<"Derived destructor called"<};

int main(){ Derived objD(1,2,3,4,5,6,7); return 0;}

继承以及内嵌对象初始化
构造函数的调用顺序与声明次序一致(注释部分)

回答2:

构造函数执行顺序:
先按继承顺序执行基类的构造函数,再执行派生类中按子对象声明顺序的构造函数,最后再执行派生类自己的构造函数。
而析构函数恰好是逆方向。