gpt4 book ai didi

c++ - 为什么这段代码说 C::f 覆盖了 A::f 而不是 B::f?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:06:19 25 4
gpt4 key购买 nike

the 3rd code example here注释说 C::f 覆盖了 A::f。为什么是这样?我的直觉告诉我它应该覆盖 B::f。

struct A { virtual void f(); };     // A::f is virtual
struct B : A { void f(); }; // B::f overrides A::f in B
struct C : virtual B { void f(); }; // C::f overrides A::f in C
struct D : virtual B {}; // D does not introduce an overrider, B::f is final in D
struct E : C, D { // E does not introduce an overrider, C::f is final in E
using A::f; // not a function declaration, just makes A::f visible to lookup
};
int main() {
E e;
e.f(); // virtual call calls C::f, the final overrider in e
e.E::f(); // non-virtual call calls A::f, which is visible in E
}

最佳答案

C++14标准的文本是(class.virtual/2):

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list, cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf. For convenience we say that any virtual function overrides itself.

因此 C::f 覆盖了所有的 A::fB::fC::f.

关于c++ - 为什么这段代码说 C::f 覆盖了 A::f 而不是 B::f?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44895206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com