C++中的一个多重继承问题:
它看起来像一个钻石问题,但事实并非如此。不能通过添加虚拟继承来解决。
struct A {
virtual void f() { cout << "A::f()" << endl; };
};
struct B : public virtual A {
void f() { cout << "B::f()" << endl;};
};
struct C : public virtual A {
void f() { cout << "C::f()" << endl;};
};
struct D : B, C { };
int main() {
D d;
B* bp = &d;
A* ap = bp;
D* dp = &d;
ap->f();
dp->f(); // compile error here because D has two candidates f() to override.
// error: request for member f is ambiguous
// error: candidates are: virtual void C::f()
// error: virtual void B::f()
}
我对吗?