有没有办法override
在 Visual C++ 2012 中强制使用 C++11 关键字?
(即如果我忘记说override
,那么我想得到一个警告/错误。)
有没有办法override
在 Visual C++ 2012 中强制使用 C++11 关键字?
(即如果我忘记说override
,那么我想得到一个警告/错误。)
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.
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:
Enable above two warnings using code.
#pragma warning(default:4263)
#pragma warning(default:4266)
在项目设置 > 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 工具。