为什么对纯虚拟函数定义是有意义的? [英] Why does it make sense to give definition for a pure virtual function?

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

问题描述

Scott在有效C ++第3版,我们只需要给它一个纯虚拟析构函数:

Scott said on Effective C++, 3rd Edition, pg. 43 that to make an abstract class, we just need to give it a pure virtual destructor:

class AWOV {                  // AWOV = "Abstract w/o Virtuals"
public:
  virtual ~AWOV() = 0;        // declare pure virtual destructor
};

然后,他继续说,有一个扭曲:我们必须提供一个纯虚拟expructor:

Then, he went on said that there is one twist: we must provide a definition for the pure virtual destructor:

AWOV::~AWOW() {}              // definition of pure virtual dtor

我的问题是,通过指定 = 0 ,对于纯虚函数,说明该函数不能对声明这个纯虚函数的类有任何定义。

My question is, by specifiying = 0, for pure virtual functions, we are saying that the function cannot have any definition for the class where this pure virtual function is declared.

为什么可以提供一个定义(即使它是空的)纯虚拟析构器在这里?

Why is it OK to provide a definition (even it is empty) for the pure virtual destructor here?

推荐答案


我们说的函数不能有任何定义类,其中声明这个纯虚函数。

"we are saying that the function cannot have any definition for the class where this pure virtual function is declared."

这不是纯虚拟的意思。纯虚拟只意味着包含的类不能被实例化(是抽象的),所以它必须是子类,子类必须重写该方法。例如,

That's not what pure virtual means. Pure virtual only means that the containing class cannot be instantiated (is abstract), so it has to be subclassed, and subclasses must override the method. E.g.,

struct A {
    virtual ~A() = 0;
};

A::~A() {}

struct B : A {};

int main()
{
    A a;  // error
    B b;  // ok
}

在这里, B 析构函数是隐式定义的。如果是另一个纯虚拟方法,则必须显式覆盖它:

Here, the B destructor is implicitly defined. If it was another method that is pure virtual, you'd have to explicitly override it:

struct A {
    virtual void foo() = 0;
};

void A::foo() {}

struct B : A {};

int main()
{
    B b;  // error
}

提供纯虚拟方法的定义,类必须是抽象的,但仍然提供一些默认行为。

Providing a definition for a pure virtual method is desirable when the base class must be abstract but still provide some default behavior.

在析构函数的特定情况下, =http://stackoverflow.com/a/677626/166749>当子类实例被销毁时,它将被自动调用。一个试图用一个没有定义的纯虚拟析构函数实例化一个类的子类的程序不会传递链接器。

In the specific case of a destructor, it has to be provided because it will be called automatically when subclass instances are destroyed. A program that tries to instantiate a subclass of a class with a pure virtual destructor without a definition will not pass the linker.

这篇关于为什么对纯虚拟函数定义是有意义的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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