使虚拟的实现也虚拟?
在 C++ 中实现纯虚函数时,是否有最佳实践指南表明实现也应该是虚拟的?理由是什么?
class Interface
{
public:
virtual void foobar() = 0;
};
class Concrete
: public Interface
{
public:
virtual void foobar();
};
When implementing a pure virtual function in C++, is there a best-practices guideline that says the implementation should also be made virtual? What is the rationale?
class Interface
{
public:
virtual void foobar() = 0;
};
class Concrete
: public Interface
{
public:
virtual void foobar();
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要紧。
Concrete
中的void foobar()
是virtual
,无论您是否这样声明它,并且它会覆盖void foobar()
> 在界面
中。It does not matter.
void foobar()
inConcrete
isvirtual
regardless whether you declare it as such and it overrides thevoid foobar()
inInterface
.尽管派生类中是否存在
virtual
关键字并不重要,但我发现它是始终 包含它,以便两年后使用您的代码的任何人都可以立即看到该类的内容比立即看到的要多。Although it doesn't matter if the
virtual
keyword is present in a derived class or not, I've found it to be an indispensable time-saving self-documenting practice to always include it, so that anyone working with your code a two years from now immediately can see that there is more to the class than what immediately meets the eye.