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
标签:函数,Derived,C++,虚析构,Base,virtual,测试,成纯,cout
From: https://www.cnblogs.com/huvjie/p/18408739