与虚拟关键字的偏差

时间:2017-04-05 09:46:19

标签: c++ inheritance

我的结构低于

struct A{
    string s;
    A() {
        cout<<"in a default\n";
    }
    A(string t): s(t) {
        cout<<"in a param \n";
    }
};

struct B: virtual public A{
    B(): A("B"){

        cout<<"in b\n";
    }
};

struct C: virtual public A {};
struct D: public B, public C {};
int main()
{
D d;
}

在C和B中使用A作为虚拟基类,输出如下

in a default
in b 

使用A作为仅B的虚拟基类,输出如下

in a default
in b
in a default

将A作为仅作为C的虚拟基类,输出如下

in a default
in a param 
in b

并且没有虚拟基类,输出如下

in a param 
in b
in a default

任何人都能解释我的偏差吗?

1 个答案:

答案 0 :(得分:0)

Virtual inheritance is there to resolve what's known as the "Diamond of death"

In summary, the issue is that if you called D::[some function in A], which A would it pick - the one from B, or the one from C, or that makes no sense that the separation exists?

You can read more about the issue here. https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem

,如何从webview发送邮件