Constructor and destructor are different from the rest of regular methods.
Constructor
不能是虚拟的
在派生类中,您要么显式调用基类的构造函数
或者,如果你没有调用基类构造函数编译器将插入调用 . 它将调用不带参数的基础构造函数 . 如果不存在这样的构造函数,则会出现编译器错误 .
struct A {};
struct B : A { B() : A() {} };
// but this works as well because compiler inserts call to A():
struct B : A { B() {} };
// however this does not compile:
struct A { A(int x) {} };
struct B : A { B() {} };
// you need:
struct B : A { B() : A(4) {} };
Destructor :
当您通过指针或引用在派生类上调用析构函数时,其中基类具有虚析构函数,将首先调用派生最多的析构函数,然后以相反的构造顺序调用其余派生类 . 这是为了确保所有内存都已正确清理 . 如果最后派生的类被调用,那么它将不起作用,因为到那时基类不会存在于内存中而你会得到段错误 .
struct C
{
virtual ~C() { cout << __FUNCTION__ << endl; }
};
struct D : C
{
virtual ~D() { cout << __FUNCTION__ << endl; }
};
struct E : D
{
virtual ~E() { cout << __FUNCTION__ << endl; }
};
int main()
{
C * o = new E();
delete o;
}
输出:
~E
~D
~C
如果基类中的方法被标记为 virtual ,则所有继承的方法都是虚拟的,所以即使你没有将 D 和 E 中的析构函数标记为 virtual ,它们仍然是 virtual ,它们仍然以相同的顺序被调用 .