/*Child is inherited from Parent*/
class Parent {
public:
Parent () //Constructor
{
cout << "\n Parent constructor called\n" << endl;
}
protected:
~Parent() //Dtor
{
cout << "\n Parent destructor called\n" << endl;
}
};
class Child : public Parent
{
public:
Child () //Ctor
{
cout << "\nChild constructor called\n" << endl;
}
~Child() //dtor
{
cout << "\nChild destructor called\n" << endl;
}
};
int main ()
{
Parent * p2 = new Child;
delete p2;
return 0;
}
如果我将 Parent
的析构函数设为虚拟,则会出现错误,那么将 protected 析构函数设为虚拟的目的是什么?
最佳答案
举个例子:假设你有一个实现引用计数的基类。您有一个 addRef
和一个 release
方法,并且您希望销毁您的对象,如果(并且仅)内部计数器通过对 release
的调用。
因此,首先您希望您的析构函数受到保护(因为您只想从 release
中销毁对象)。
如果你打算从你的类派生,你也希望你的析构函数是虚拟的,因为当你想通过指向基类的指针销毁子对象时,你需要一个虚拟析构函数(感谢@sharptooth 的提示。 ..)
关于c++ - 将 protected 析构函数虚拟化是否有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8970466/