问题描述
在浏览一些旧代码时,我遇到类似以下内容的情况:
class Base
{
public:
virtual int Func();
...
};
class Derived:public Base
{
public:
int Func(); // Missing'virtual'qualifier
...
};
代码编译正常(MS VS2008),没有警告(级别4),它按预期工作 -
Func
是虚拟的,即使在派生类中缺少虚拟限定符。现在,除了引起一些混乱,这个代码有什么危险,或者我应该改变它,添加 virtual
限定符?
virtual
将继承到派生类中的所有覆盖函数。添加关键字的唯一真正好处是表示你的意图一个随机的观察者Derived类定义将立即知道 Func
是虚拟的。 甚至扩展Derived的类都有虚拟Func方法。
参考:。向下滚动页面以查看
Whilst trawling through some old code I came across something similar to the following:
class Base
{
public:
virtual int Func();
...
};
class Derived : public Base
{
public:
int Func(); // Missing 'virtual' qualifier
...
};
The code compiles fine (MS VS2008) with no warnings (level 4) and it works as expected - Func
is virtual even though the virtual qualifier is missing in the derived class. Now, other than causing some confusion, are there any dangers with this code or should I change it all, adding the virtual
qualifier?
The virtual
will be carried down to all overriding functions in derived classes. The only real benefit to adding the keyword is to signify your intent a casual observer of the Derived class definition will immediately know that Func
is virtual.
Even classes that extend Derived will have virtual Func methods.
Reference: Virtual Functions on MSDN. Scroll down the page to see
这篇关于在函数声明中缺少“虚拟”限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!