C ++“接口"是否应具有虚拟析构函数 [英] Should C++ 'interfaces' have a virtual destructor

查看:65
本文介绍了C ++“接口"是否应具有虚拟析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
类似C ++接口的类的析构函数

考虑一个用于对接口进行建模的C ++抽象类的简单示例:

Consider a simple example of a C++ abstract class, used to model an interface:

class IAnimal
{
  virtual void walk()=0;
  virtual ~IAnimal(){}
};

拥有析构函数更好吗?我不认为析构函数可以是纯虚拟的,至少我的测试给出了链接器错误,所以应该包括一个空的析构函数吗?

Is it better to have the destructor, or not? I don't think the destructor can be pure virtual, at least my tests give linker errors, so should an empty destructor be included?

编辑:抱歉,错字了.这是一个析构函数,而不是一个构造函数.

sorry, typo. It's a destructor not a constructor.

推荐答案

您应始终将虚拟析构函数与接口一起使用.恰当的例子:

You should always use a virtual destructor with interfaces. Case in point:

IAnimal* animal = new Lion();
delete animal;

现在它将使用什么析构函数?绝对不是Lion的析构函数,因为接口不知道Lion的析构函数.

Now what destructor is it going to use? Definately not the Lion's destructor because the interface doesn't know about Lion's destructor.

因此,如果您的界面没有内存管理,请执行以下操作:

So, have this if your interface has no memory management:

virtual ~IAnimal(){}

这篇关于C ++“接口"是否应具有虚拟析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆