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 functionvfis declared in a classBaseand in a classDerived, derived directly or indirectly fromBase, a member functionvfwith the same name, parameter-type-list (11.3.5), cv-qualification, and ref-qualifier (or absence of same) asBase::vfis declared, thenDerived::vfis 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
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
