在函数声明中缺少“虚拟”限定符 [英] Missing 'virtual' qualifier in function declarations
问题描述
在浏览一些旧代码时,我遇到类似以下内容的情况:
class Base
{
public:
virtual int Func();
...
};
class Derived:public Base
{
public:
int Func(); // Missing'virtual'qualifier
...
};
代码编译正常(MS VS2008),没有警告(级别4),它按预期工作 - Func
是虚拟的,即使在派生类中缺少虚拟限定符。现在,除了引起一些混乱,这个代码有什么危险,或者我应该改变它,添加 virtual
限定符?
Func
是虚拟的。 甚至扩展Derived的类都有虚拟Func方法。
参考:虚拟功能。向下滚动页面以查看
在
声明重写函数时,可以使用 virtual a
派生类,但它是不必要的;
虚函数的覆盖是
总是虚的。
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
The virtual keyword can be used when declaring overriding functions in a derived class, but it is unnecessary; overrides of virtual functions are always virtual.
这篇关于在函数声明中缺少“虚拟”限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!