C++虚函数(12) - 纯虚析构函数

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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值