据我所知,如果我们想调用派生对象的析构函数,该派生对象已分配给指向base的指针,我们希望将基本析构函数设为虚拟。 但是,如果我们有这样的事情:
#include <iostream>
using namespace std;
class base
{
public:
base() { cout << "Base Constructor Called\n"; }
virtual ~base() { cout << "Base Destructor called\n"; }
};
class derived1 :public base
{
public:
derived1() { cout << "Derived1 constructor called\n"; }
~derived1() { cout << "Derived1 destructor called\n"; }
};
class derived2 : public derived1
{
public:
derived2() { cout << "Derived2 constructor called\n"; }
~derived2() { cout << "Derived2 destructor called\n"; }
};
class derived3 : public derived2
{
public:
derived3() { cout << "Derived3 constructor called\n"; }
~derived3() { cout << "Derived3 destructor called\n"; }
};
我们有这样的主要功能:
int main (){
base* ptr=new derived3;
delete ptr;
输出为:
Base Constructor Called
Derived1 constructor called
Derived2 constructor called
Derived3 constructor called
Derived3 destructor called
Derived2 destructor called
Derived1 destructor called
Base Destructor called
这会调用base,derived1,derived2和derived3析构函数,它们运行得很好。我们只将基础析构函数设为虚拟 为什么没有必要将derived1和derived2析构函数作为虚拟来产生相同的结果?
答案 0 :(得分:2)
从具有虚析构函数的类派生的所有类都隐式具有虚拟析构函数。
这适用于类层次结构中的任何成员函数。
答案 1 :(得分:2)
将函数声明为virtual
后,它在所有派生类中隐式保留virtual
。