Are function attributes inherited?(函数属性是否继承?)
问题描述
如果我有一个带有 属性的虚函数
[[nodiscard]] virtual bool some_function() = 0;
该属性是否会隐式应用于该函数的覆盖?
Does that attribute get implicitly applied to overrides of that function?
bool some_function() override;
或者我需要再次使用该属性吗?
Or do I need the attribute again?
[[nodiscard]] bool some_function() override;
推荐答案
我在 C++17 的措辞中看不到任何证据表明属性是由覆盖函数继承的.
I can't see any evidence in the C++17 wording that attributes are inherited by overriding functions.
我能找到的最相关的部分是覆盖规则:
The most relevant section I can find is the rules for overriding:
[class.virtual]/2:
如果在类 Base
和类 中声明了虚成员函数
,直接或间接派生自vf
>派生Base
,成员函数vf
,同名,parameter-type-list (11.3.5)、cv-qualification 和 ref-qualifier(或没有相同)作为 Base::vf
被声明,然后 Derived::vf
也是虚拟的(无论它是否如此声明)并且它覆盖 Base::vf
.[..]
[class.virtual]/2:
If a virtual member functionvf
is declared in a classBase
and in a classDerived
, derived directly or indirectly fromBase
, a member functionvf
with the same name, parameter-type-list (11.3.5), cv-qualification, and ref-qualifier (or absence of same) asBase::vf
is declared, thenDerived::vf
is also virtual (whether or not it is so declared) and it overridesBase::vf
. [..]
虽然这段话从稍微不同的角度解决了这个问题,但我认为这足以表明只有虚拟性是继承的"(并且在决定一个函数是否覆盖另一个函数时,属性根本不会发挥作用).话虽如此,我认为这有点未充分说明,至少可以用一个澄清说明来做.
While this passage attacks the problem from a slightly different angle, I think it's enough to show that only virtualness is "inherited" (and that attributes don't come into play at all when deciding whether one function overrides another). That being said, I think this is slightly underspecified and could do with a clarifying note at the very least.
当然,这很快就会变得复杂.举个例子:
Of course, this quickly gets complicated. Given the below example:
struct B {
[[nodiscard]] virtual bool foo() { return true; }
};
struct D : B {
bool foo() override { return false; }
};
int main() {
D().foo();
}
Clang 不会发出警告.但是,通过基指针访问该函数,它会.
Clang will not issue a warning. However, access the function through a base pointer and it will.
struct B {
[[nodiscard]] virtual bool foo() { return true; }
};
struct D : B {
bool foo() override { return false; }
};
int main() {
D d;
((B*)&d)->foo();
}
这对你的问题意味着什么,我不确定.
What that means for your question, I'm not sure.
再次,我想从标准中看到更多关于这个主题的指导.
Again, I'd like to see a bit more guidance from the standard on this topic.
这篇关于函数属性是否继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:函数属性是否继承?


基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01