struct A {
virtual void foo() { std::cout << "a";};
};
struct B:public virtual A {
void foo() { std::cout << "b";}
};
struct C:public virtual A {
void foo() { std::cout << "c";}
};
struct D:public B, public C {
};
int main() {
return 0;
}
Run Code Online (Sandbox Code Playgroud)
因此,在编译时会出现以下错误:
\main.cpp:16:8: error: no unique final overrider for 'virtual void A::foo()' in 'D'
struct D:public B, public C {
Run Code Online (Sandbox Code Playgroud)
如果我们将B和C结构的继承设为非虚拟的,则代码将正确编译而没有任何错误(但是,如果我们调用dd.foo(),则错误当然会发生)。那有什么区别呢?为什么当我们虚拟继承我们的类时出现错误,而如果直接继承则没有错误呢?