当在c++中覆盖一个类(使用虚析构函数)时,我在继承类上再次实现了虚析构函数,但我需要调用基析构函数吗?
如果是这样的话,我想应该是这样的……
MyChildClass::~MyChildClass() // virtual in header
{
// Call to base destructor...
this->MyBaseClass::~MyBaseClass();
// Some destructing specific to MyChildClass
}
我说的对吗?
不,你不需要调用基析构函数,基析构函数总是由派生析构函数调用。请参阅我的相关回答在这里的破坏顺序。
要理解为什么要在基类中使用虚析构函数,请参阅下面的代码:
class B
{
public:
virtual ~B()
{
cout<<"B destructor"<<endl;
}
};
class D : public B
{
public:
virtual ~D()
{
cout<<"D destructor"<<endl;
}
};
当你这样做时:
B *pD = new D();
delete pD;
然后,如果在B中没有虚析构函数,则只会调用~B()。但是由于您有一个虚析构函数,首先将调用~D(),然后是~B()。
不,你永远不会调用基类析构函数,它总是自动调用,就像其他人指出的那样,但这里是概念的证明和结果:
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相同。