在函数声明中缺少“虚拟”限定符 [英] Missing 'virtual' qualifier in function declarations

查看:99
本文介绍了在函数声明中缺少“虚拟”限定符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浏览一些旧代码时,我遇到类似以下内容的情况:

  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方法。



参考:虚拟功能。向下滚动页面以查看



声明重写函数时,可以使用 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屋!

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