当用C ++覆盖一个类(使用虚拟析构函数)时,我在继承类上再次将析构函数实现为虚拟,可是我是否须要调用基本析构函数? 函数
若是是这样,我想它就是这样...... this
MyChildClass::~MyChildClass() // virtual in header { // Call to base destructor... this->MyBaseClass::~MyBaseClass(); // Some destructing specific to MyChildClass }
我对吗? spa
不,你永远不会调用基类析构函数,它老是像其余人指出的那样自动调用,但这里是结果的概念证实: code
class base { public: base() { cout << __FUNCTION__ << endl; } ~base() { cout << __FUNCTION__ << endl; } }; class derived : public base { public: derived() { cout << __FUNCTION__ << endl; } ~derived() { cout << __FUNCTION__ << endl; } // adding call to base::~base() here results in double call to base destructor }; int main() { cout << "case 1, declared as local variable on stack" << endl << endl; { derived d1; } cout << endl << endl; cout << "case 2, created using new, assigned to derive class" << endl << endl; derived * d2 = new derived; delete d2; cout << endl << endl; cout << "case 3, created with new, assigned to base class" << endl << endl; base * d3 = new derived; delete d3; cout << endl; return 0; }
输出是: 继承
case 1, declared as local variable on stack base::base derived::derived derived::~derived base::~base case 2, created using new, assigned to derive class base::base derived::derived derived::~derived base::~base case 3, created with new, assigned to base class base::base derived::derived base::~base Press any key to continue . . .
若是将基类析构函数设置为虚拟的,那么案例3的结果将与案例1和2相同。 ci
不,您不须要调用基础析构函数,派生析构函数老是为您调用基础析构函数。 请在此处查看个人相关答案以了解销毁顺序 。 get
要了解为何要在基类中使用虚拟析构函数,请参阅如下代码: it
class B { public: virtual ~B() { cout<<"B destructor"<<endl; } }; class D : public B { public: virtual ~D() { cout<<"D destructor"<<endl; } };
当你这样作时: io
B *pD = new D(); delete pD;
而后,若是B中没有虚拟析构函数,则只调用~B()。 可是由于你有一个虚拟的析构函数,因此先调用~D()而后调用~B()。 class
不,它是自动调用的。
不,析构函数会按照相反的构造顺序自动调用。 (基础课最后)。 不要调用基类析构函数。
其余人说了什么,但也注意到你没必要在派生类中声明析构函数virtual。 一旦声明了析构函数virtual,就像在基类中那样,全部派生的析构函数都是虚拟的,不管你是否声明它们。 换一种说法:
struct A { virtual ~A() {} }; struct B : public A { virtual ~B() {} // this is virtual }; struct C : public A { ~C() {} // this is virtual too };