在运行下面的代码,为何是基类的构造函数导出的第一即使我们首先声明派生类的对象。为什么基类的构造函数首先调用?
#include<iostream>
using namespace std;
class base {
public:
base()
{ cout<<"Constructing base \n"; }
~base()
{ cout<<"Destructing base \n"; }
};
class derived: public base {
public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};
int main(void)
{
derived *d = new derived(); //d is defined ahead of the base class object
base *b = d;
delete b;
return 0;
}
你还会期待什么?为什么? – user0042
提示:在'derived'里面有一个'base' **子对象**。 – StoryTeller
问题不清楚。你可以解释吗? – MoraRockey