纯虚析构函数必须有定义(可以是空的),一般就给一个空的
#include <iostream>
class A
{
public:
explicit A(int x) : m_nX(x) {}
virtual ~A() = 0;// 纯虚析构函数必须有定义并且会执行
virtual void f1() = 0 /*{ std::cout << "A::f1()" << std::endl; }*/;// 纯虚成员函数不必有定义,有了也不会执行,没有意义
private:
int m_nX;
};
A::~A()
{
std::cout << "~A" << std::endl;
}
class B : public A
{
public:
explicit B(int x) : A(x) {}
virtual ~B() override {};
virtual void f1() override { std::cout << "B::f1()" << std::endl; };
};
int main()
{
B b(1);// 如果纯虚析构函数没有定义的话就有:error LNK2019: 无法解析的外部符号 "public: virtual __thiscall A::~A(void)" (??1A@@UAE@XZ),
// 该符号在函数 "public: virtual __thiscall B::~B(void)" (??1B@@UAE@XZ) 中被引用
b.f1();
return 0;
}