程序如下:
#include<iostream.h>
class Data
{
public:
Data(int x)
{
Data::x=x;
cout<<"Data cons."<<endl;
}
~Data(){cout<<"Data des."<<endl;}
private:
int x;
};
class Base
{public:
Base(int x):dl(x){cout<<"Base cons."<<endl;}
~Base(){cout<<"Base des."<<endl;}
private:
Data dl;
};
class Derived:public Base
{
public:
Derived(int x):Base(x),d2(x){cout<<"Derived cons."<<endl;}
~Derived(){cout<<"Derived des."<<endl;}
private:
Data d2;
};
void main()
{
Derived obj(5);
}
我觉得结果应该是先基类Base cons后子对象Data cons;答案不是晕那
參考答案:因为你的Base 类里面有一个Data dl; 属性!
所以程序在调用Base类的构造方法之前会先调用 Data的构造方法
^_^