#include <iostream>
struct A {
virtual void f(){
std::cout<<"1\n";
}
};
struct B : A {
};
struct C : A {
void f(){
std::cout<<"abc\n";
}
};
struct D : B, C {
};
int main(){
D mostDerived{};
D* ptr = &mostDerived;
B* bptr = ptr;
A* aptr = bptr;
aptr->f();
}
考虑上面的代码,outcome是1
.但是,由于标准的说法,我对这个结果表示怀疑:
class.virtual#def:final_overrider
For convenience we say that any virtual function overrides itself. A virtual member function C::vf of a class object S is a final overrider unless the most derived class of which S is a base class subobject (if any) declares or inherits another member function that overrides vf.
Members of a base class other than constructors are said to be inherited by the derived class. Constructors of a base class can also be inherited as described in [namespace.udecl].
IIUC,考虑 A
类型的基类子对象在 B 和 C
中作为A1
, A2
分别。在我的示例中,最派生类是 D
,根据上面的规则,对于类B
, 最后的覆盖是 A::f
这是继承自 A
, 类 C
, 最后的覆盖是 C::f
在类 C
中声明, 和类 D
, 它源自 B
和 C
, 因此它将从 B
继承这些成员和 C
.自 C::f
覆盖 A::f
, 所以根据规则 unless **the most derived class of which S is a base class subobject** (if any) declares or **inherits another member function that overrides vf**
,其中考虑 A1
作为S
(即 A1
是类 D
的子对象),其中 D
继承了 another member function that overrides vf
这是C::f
.这意味着,子对象的最终覆盖 A1
应该是 C::f
,因此,我想知道为什么结果不是 abc
而不是 1
?
另一个问题是:
struct A {
virtual void f(){
std::cout<<"1\n";
}
};
struct B : A {
void f(){}
};
struct C : A {
void f(){}
};
struct D : B, C {
};
两者都是 B::f
和 C::f
重写虚函数 A::f
, 但它们不会相互覆盖,所以函数会做 D
继承?或者两者都由 D
继承?
如果我遗漏了什么,如何正确阅读上述规则。或者对于第一个问题,上述规则是否确实不清楚造成误解?
最佳答案
... A virtual member function C::vf of a class object S is a final overrider unless the most derived class of which S is a base class subobject (if any) declares or inherits another member function that overrides vf.
引用的规则可能存在误导性,因此存在缺陷。
vf
仅仅被 任何 类型 B
的基重写应该是不够的,但它应该被特别重写为 < em>那个基础子对象。在您的示例中,有两个 A
类型的基本子对象,其中一个覆盖了 A::f
而另一个没有覆盖。
so which the function does D inherits? or both are inherited by D?
两者都是继承的。
关于c++ - 关于标准中虚函数描述的一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63992216/