class Base {
public:
virtual ~Base() { cout << "~Base" << '\n'; }
};
class Derived : public Base {
public:
~Derived() { cout << "~Derived" << '\n'; }
};
int main()
{
{
Base* b = new Derived;
delete b;
}
system("pause");
return EXIT_SUCCESS;
}
析構順序輸出:
~Derived
~Base
如果,把基類的解構函式設定成純虛擬函式,也必須要定義,不然編譯不過,只定義派生類的函式時不行的。
將解構函式設定成純虛,目的可能是不能讓類例項的作用。
class Base
{
public:
virtual ~Base() = 0;
};
Base::~Base() { cout << "~Base" << '\n'; } // 必須要定義,不然編譯不過。
class Derived : public Base
{
public:
~Derived() { cout << "~Derived" << '\n'; }
};
輸出:
~Derived
~Base