使用纯虚拟函数与body? [英] Use-cases of pure virtual functions with body?

查看:96
本文介绍了使用纯虚拟函数与body?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近才知道在C ++中纯虚函数可以有选择地有一个主体。

I recently came to know that in C++ pure virtual functions can optionally have a body.

这些函数的真实用例是什么?

What are the real-world use cases for such functions?

推荐答案

p>经典是一个纯虚拟析构函数:

The classic is a pure virtual destructor:

class abstract {
  public: 
    virtual ~abstract() = 0;
};

abstract::~abstract() {}

因为没有别的东西,所以,你想要的类是抽象的,但你必须提供一个实现,但是,因为派生类的析构函数明确地调用你的。是的,我知道,一个很愚蠢的教科书的例子,但因为这是一个经典。它必须已在 C ++编程语言的第一版中。

You make it pure because there's nothing else to make so, and you want the class to be abstract, but you have to provide an implementation nevertheless, because the derived classes' destructors call yours explicitly. Yeah, I know, a pretty silly textbook example, but as such it's a classic. It must have been in the first edition of The C++ Programming Language.

无论如何,我不记得有没有真正需要实现纯虚函数的能力。对我来说,似乎这个功能的唯一原因是因为它必须明确禁止,Stroustrup没有看到一个原因。

Anyway, I can't remember ever really needing the ability to implement a pure virtual function. To me it seems the only reason this feature is there is because it would have had to be explicitly disallowed and Stroustrup didn't see a reason for that.

如果你觉得你需要这个功能,你的设计可能是错误的。

If you ever feel you need this feature, you're probably on the wrong track with your design.

这篇关于使用纯虚拟函数与body?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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