Is there a way to flag (at compile time) “overridden” methods whose signatures don't match base signature?

偶尔善良 提交于 2019-12-10 13:19:28

问题


Basically, I want the C# compiler functionality of its override keyword in my C++ code.

class Base
{
   virtual int foo(int) const;
};

class Derived : public Base
{
   virtual int foo(int); // wanted to override Base, but forgot to declare it const
};

As we all know, the above code will compile fine, but yield some strange runtime behavior. I would love my C++ compiler to catch my poor implementation with something like C#'s override keyword. Are there any keywords like "override" being introduced into C++, or are we stuck with #define override virtual to show our intent? (actually, I do not do this - I hate using the preprocessor to "extend" the language).


回答1:


If you can't wait for C++0x, Visual C++ already has this override keyword. (Since 2005 I believe). There the syntax is:

virtual int foo(int) override;

You're not obliged to type it, however. And its a non-standard microsoft extension.




回答2:


As far I know, this is not possible with the current standard. You can do it in the upcoming C++0x. See here for more details: Explicit virtual function overrides



来源:https://stackoverflow.com/questions/3887674/is-there-a-way-to-flag-at-compile-time-overridden-methods-whose-signatures-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!