【发布时间】:2017-12-21 02:03:18
【问题描述】:
在运行下面的代码时,为什么我们先声明了派生类的对象,还是先派生了基类的构造函数。
#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;
}
【问题讨论】:
-
您还能期待什么?为什么?
-
提示:
derived内部有一个base子对象。 -
对象是自下而上构造的。
derived有一个base类型的基类,因此当您创建derived的实例时,您会看到一系列构造函数调用,例如:base->derived。您如何在墙壁尚未到位的房屋上安装屋顶?自下而上。就是这样。 -
请查看类数据初始化规则here。
-
@samfisher 它打印 constructing base 然后 constructing derived,因为你必须首先初始化一个
base对象如果你想创建一个derived的话。前者是后者的子对象。
标签: c++ oop inheritance