如果我有一个带有 attribute 的虚函数
[[nodiscard]] virtual bool some_function() = 0;
该属性是否隐式应用于该函数的覆盖?
bool some_function() override;
或者我是否需要再次使用该属性?
[[nodiscard]] bool some_function() override;
最佳答案
我给 C++ 委员会发了一封电子邮件,特别是 Core工作组,并提供了上述示例。
科里克莱默
It is currently unclear from the standard if attributes applied to virtual functions are inherited.
响应:
They are not. For them to be inherited, the Standard would have to explicitly say so, and it does not.
科里克莱默:
[After providing above code example] In the above example, I would expect both lines calling
foo()
to emit a compiler warning. I would hope that the attribute applies to all derived functions for consistency.
响应:
That's one perspective. Another is that, especially with covariant return types where the derived function returns a different type from that of the base function, it might very well be useful to make the base return type
[[nodiscard]]
but not the derived return type. There's currently no way to mark the derived function as not-[[nodiscard]]
.More generally, it seems reasonable to get a different set of attributes when calling a derived function from those you get when calling the base function. If you know you have a derived class object, you have more specific information and behavior than if all you know is that it's a base class object, and attributes on member functions are part of that extra knowledge.
回复 Mike Miller C++ 核心工作组成员(2018 年 3 月 30 日)。
关于c++ - 函数属性是否继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49576298/