简体   繁体   English

覆盖非虚拟功能

[英]override on non-virtual functions

The C++11 FDIS it says 它说的是C ++ 11 FDIS

If a virtual function is marked with the virt-specifier override and does not override a member function of a base class, the program is ill-formed. 如果使用virt-specifier覆盖标记了虚函数并且不覆盖基类的成员函数,则程序格式错误。 [ Example: [示例:

 struct B { virtual void f(int); }; struct D : B { void f(long) override; // error: wrong signature overriding B::f void f(int) override; // OK }; 

What if B::f would not have been marked virtual? 如果B::f不会被标记为虚拟怎么办? Is the program ill-formed, then? 程序格式错误吗? Or is override then to be ignored`. 还是被override然后被忽略`。 I can not find any handling of this case in the std text. 我在标准文本中找不到这种情况的任何处理。

Update 1/2 (merged) I forwarded a request to the C++ Editors to look into things. 更新1/2 (合并)我将请求转发给C ++编辑器以调查问题。 Thanks Johannes to pointing that out to me. 感谢约翰内斯向我指出这一点。

  • "void f(long) override" does not override a function, esp. “无效f(long)覆盖”不会覆盖函数,特别是。 no virtual one, 没有虚拟的,
  • therefore it is not virtual 因此它不是虚拟的
  • therefore the text "If a virtual function is marked with..." does not apply 因此,文本“如果虚拟功能标记有...”不适用
  • therefore the example does not match the text. 因此,该示例与文本不匹配。

But by realizing this I found, that the intention of the "override" contextual keyword can not be met: if a typo in the function name or the wrong argument type does make the function itself non-virtual, then the standard's text never applies -- and "override" is rendered useless. 但是通过意识到这一点,我发现无法满足“ override”上下文关键字的意图:如果函数名称中的错字或错误的参数类型确实使函数本身不是虚拟的,那么该标准的文本将永远不适用- -而“替代”则变得无用。

The best possible solution may be 最好的解决方案可能是

  • putting "virtual" in front of the example's functions 将“虚拟”放在示例功能的前面

What if B::f would not have been marked virtual? 如果B::f不会被标记为虚拟怎么办? Is the program ill-formed, then? 程序格式错误吗?

Yes, it is. 是的。 Because in order to override something, that something has to be virtual. 因为为了覆盖某些内容,所以某些内容必须是虚拟的。 Otherwise it's not overriding , it's hiding . 否则,它不会被覆盖 ,而是会被隐藏 So, the positive answer follows from the quote in your question. 因此,肯定的答案来自您问题的引文。

如果B:f是非虚拟的,则两个 D:f函数都将格式错误。

Yes, the program is ill formed when override is added to any non-virtual function. 是的,将override添加到任何非虚拟函数时,程序格式不正确。

Generally, functions with differing signatures (overloaded), are as different as functions with different names. 通常,具有不同签名(重载)的功能与具有不同名称的功能一样。 The example given in the Spec is not meant to imply that the function name effects override . 在规格中给出的例子并不意味着暗示函数名影响override It's meant to show the common error that override is designed to prevent. 它旨在显示override旨在防止的常见错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM