我正在阅读关于java中的钻石继承问题。 所以想知道其他语言是如何解决的,并发现c ++已经解决了它。 我发现这个虚拟继承如何解决“钻石”(多重继承)歧义? 。 然后我在在线c ++编译器中尝试了这段代码。 我试过了
#include <iostream> using namespace std; class A { public: void eat(){ cout<<"A";} }; class B: virtual public A { public: void eat(){ cout<<"B";} }; class C: virtual public A { public: void eat(){ cout<<"C";} }; class D: public B,C { public: void eat(){ cout<<"D";} }; int main() { A *a = new D(); a->eat(); }有效 。 然后我想调用B的吃并改变A * a = new D(); 至
B *a = new D();这太有用了。但是当我尝试的时候
C *a = new D();它扔了,错了
错误:'C'是'D'C * a = new D()的难以接近的基础;
为什么单独使用C这个错误? 它甚至是公开的。 那为什么它无法访问?
所以我做的是我改变了继承的顺序
class D: public C,B { public: void eat(){ cout<<"D";} };现在C * a = new D(); 但是B * a = new D(); 失败了。
为什么会这样?
订单重要吗?
当我用Google搜索时,我发现了这个stackoverflow链接 ,但发现它是为构造函数。 我不明白为什么这个案子失败了。
如果我的问题很愚蠢,请原谅,因为我对C ++很陌生。我习惯于只有没有多重继承的java。
I was reading about diamond inheritance problem in java . So wanted to know how other languages have solved and found that c++ has solved it . And I found this How does virtual inheritance solve the "diamond" (multiple inheritance) ambiguity? . Then I tried this code in online c++ compiler . I tried
#include <iostream> using namespace std; class A { public: void eat(){ cout<<"A";} }; class B: virtual public A { public: void eat(){ cout<<"B";} }; class C: virtual public A { public: void eat(){ cout<<"C";} }; class D: public B,C { public: void eat(){ cout<<"D";} }; int main() { A *a = new D(); a->eat(); }It worked . Then I wanted to invoke B's eat and changed A *a = new D(); to
B *a = new D();and this too worked .But when I tried
C *a = new D();It threw and error
error: 'C' is an inaccessible base of 'D' C *a = new D();
Why with C alone this error ? It is even public . Then why its not accessible ?
So what I did was I changed the order of inheritance to
class D: public C,B { public: void eat(){ cout<<"D";} };And now C *a = new D(); passed but B *a = new D(); failed .
Why is it so ?
Is the order important ?
When I googled I found this stackoverflow link, but found that it is for constructors . I could not understand why this case fails .
Please forgive if my question is stupid , as I am damn new to C++ .I am used to only java where there is no multiple inheritance .
最满意答案
D从B公开继承,但私下从C继承。 如果要从两者公开继承,请使用此选项:
class D: public B, public C { public: void eat(){ cout<<"D";} };D inherits publicly from B, but privately from C. Use this if you want to inherit publicly from both:
class D: public B, public C { public: void eat(){ cout<<"D";} };更多推荐
发布评论