C++中析构函数能否为纯虚函数?
可以!!C++中定义一个纯虚析构函数是合法的,并且最重要的一点是如果某个类包含纯虚析构函数,则类必须给此函数定义函数体。
看起来这种现象很奇怪,纯虚函数怎么会需要定义函数体呢?但是,因为析构函数的调用顺序总是与构造顺序相反,这就意味着派生类的析构总是先被调用,然后再调用基类的析构。
如果纯虚析构函数没有给出定义,则对象析构时如何调用这个函数?因此,编译器以及链接器强制规定纯虚析构函数的函数体必须存在。
参考下面的程序:
#include <iostream>
class Base {
public:
virtual ~Base() = 0; // 纯虚析构函数
};
class Derived : public Base {
public:
~Derived() { std::cout << "~Derived() is executed"; }
};
int main() {
Base* b = new Derived();
delete b;
return 0;
}
编译时,链接器会报下面的错误:
linux平台(gcc 4.8.5 in CentOS 7.2):
In function `Derived::~Derived()':
(.text._ZN7DerivedD2Ev[_ZN7DerivedD5Ev]+0x2e): undefined reference to `Base::~Base()'
windows平台(visual studio 2015):
error LNK2019: 无法解析的外部符号 "public: virtual __thiscall Base::~Base(void)" (??1Base@@UAE@XZ),该符号在函数 "public: virtual __thiscall Derived::~Derived(void)" (??1Derived@@UAE@XZ) 中被引用
下面程序中,提供了纯虚析构函数的定义,则程序编译运行正常。
#include <iostream>
class Base {
public:
virtual ~Base() = 0; // 纯虚析构函数
};
Base::~Base() { std::cout << "Pure virtual destructor is called" << std::endl; }
class Derived : public Base {
public:
~Derived() { std::cout << "~Derived() is executed" << std::endl; }
};
int main() {
Base* b = new Derived();
delete b;
return 0;
}
运行结果:
~Derived() is executed
Pure virtual destructor is called