C ++使用纯虚方法覆盖纯虚方法 [英] C++ override pure virtual method with pure virtual method
问题描述
用另一个纯虚方法重写纯虚方法是否有意义?是否有任何功能差异或代码风格的理由,喜欢下面的选项之一比另一个?
Does it ever make sense to override a pure virtual method with another pure virtual method? Are there any functional differences or perhaps code style reasons to prefer one of the following options over the other?
class Interface {
public:
virtual int method() = 0;
};
class Abstract : public Interface {
public:
int method() override = 0;
};
class Implementation : public Abstract {
public:
int method() override { return 42; }
};
与
class Interface {
public:
virtual int method() = 0;
};
class Abstract : public Interface {};
class Implementation : public Abstract {
public:
int method() override { return 42; }
};
推荐答案
两个代码产生相同的效果:class 抽象
是抽象的,你不能实例化它。
Both codes produce the same effect: class Abstract
is abstract and you can't instantiate it.
但是这两种形式之间存在语义差异:
There is however a semantic difference between the two forms:
- 第一种形式清楚地提醒,类
Abstract
是抽象的它的名字不会自我分割足够 ;-))。它不仅提醒它:它也确保它通过确保该方法是纯虚拟的。 - 第二种形式表示类
Abstract
完全继承Interface
。它是抽象的,当且仅当它的基类是。
- The first form reminds clearly that the class
Abstract
is abstract (just in case it's name would not be self-sepaking enough ;-) ). Not only does it reminds it: it also ensures it by making sure that method is pure virtual. - The second form means that the class
Abstract
inherits everything exactly fromInterface
. It's abstract if and only if its base class is.
这会对您的代码的未来发展造成影响。例如,如果有一天你改变主意,并希望界面具有 method()
的默认实现:
This has consequences on future evolutions of your code. For instance, if one day you change your mind and want interface to have a default implementation for method()
:
- 在第一种形式
Absract
保持抽象,不会继承方法的默认实现。 - 第二种形式确保
Abstact
将继续继承并且行为与接口
。
- In the first form
Absract
remains abstract and will not inherit the default implementation of the method. - The second form ensures that
Abstact
would continue to inherit and behave exactly asInterface
.
我发现第二种形式更直观,可以更好地分离关注点。但我可以想象,可能有一些情况下,第一种形式真的有意义。
Personnally I find that the second form is more intuitive and ensures better separation of concerns. But I can imagine that there could be some situations were the first form could really make sense.
这篇关于C ++使用纯虚方法覆盖纯虚方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!