有没有办法标记(在编译时)“覆盖”签名与基本签名不匹配的方法?
基本上,我希望 C++ 代码中的 override
关键字具有 C# 编译器功能。
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
};
众所周知,上面的代码可以很好地编译,但会产生一些奇怪的运行时行为。我希望我的 C++ 编译器能够使用 C# 的 override
关键字来捕获我的糟糕实现。 C++ 中是否引入了诸如“override”之类的关键字,或者我们是否坚持使用 #define override virtual
来表明我们的意图? (实际上,我不这样做 - 我讨厌使用预处理器来“扩展”语言)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,按照目前的标准这是不可能的。您可以在即将推出的 C++0x 中做到这一点。有关更多详细信息,请参阅此处:显式虚函数覆盖
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
如果您等不及 C++0x,Visual C++ 已经有这个 override 关键字。 (我相信自 2005 年以来)。语法是:
但是,您不必键入它。它是一个非标准的微软扩展。
If you can't wait for C++0x, Visual C++ already has this override keyword. (Since 2005 I believe). There the syntax is:
You're not obliged to type it, however. And its a non-standard microsoft extension.