57

有没有办法override在 Visual C++ 2012 中强制使用 C++11 关键字?

(即如果我忘记说override,那么我想得到一个警告/错误。)

4

2 回答 2

22

C++11 几乎拥有了你想要的东西。

最初,该override关键字是一个更大的提案(N2928)的一部分,其中还包括强制使用它的能力:

class A
{
  virtual void f();
};

class B [[base_check]] : public A
{
    void f();  // error!
};

class C [[base_check]] : public A
{
  void f [[override]] ();  // OK
};

该属性会导致在不使用关键字base_check的情况下覆盖虚函数是错误的。override

还有一个hiding属性表示函数隐藏了基类中的函数。Ifbase_check被使用并且一个函数从基类中隐藏一个而不使用hiding它是一个错误。

But most of the proposal was dropped and only the final and override features were kept, as "identifiers with special meaning" rather than attributes.

于 2012-11-04T22:28:01.167 回答
14

There are few ways to do this in VC++ and equivalent ways with GCC as well.

VC++

Below are the relevant warning numbers in VC++:

C4263 (level 4) 'function': member function does not override any base class virtual member function
C4266 (level 4) 'function': no override available for virtual member function from base 'type'; function is hidden

To enable these two warnings, you can use one of following options:

  1. Set warning level to 4 in project settings and then disable the warnings you don't want. This is my prefered way. To disable unwanted Level 4 warnings, go to project settings > C/C++ > Advanced and then enter warning numbers in Disable Specific Warnings box.
  2. Enable above two warnings using code.

    #pragma warning(default:4263)
    #pragma warning(default:4266)
    
  3. 在项目设置 > C/C++ > 命令行中启用以上两个警告,然后输入 /w34263 /w34266。这里 /wNxxxx 选项意味着在 N 级启用 xxxx 警告(N = 3 是默认级别)。您还可以执行 /wdNxxxx 来禁用 N 级中的 xxxx 警告。

海合会

GCC 5.1+ 添加了新的警告建议覆盖,您可以将其作为命令行选项传递-Wsuggest-override

Clang 3.5+ 有-Winconsistent-missing-override,但是这只检测某些覆盖成员或基类使用override但其他覆盖成员不使用的情况。您可能还想看看 clang-tidy 工具。

于 2016-12-12T21:05:26.043 回答