为什么C++需要虚继承

先看个编译多继承带来的编译错误

/*************************************************************************
    > File Name: muti_inherit.cpp
    > Author: guoqingyao
    > Mail: stepbystepto@163.com 
    > Created Time: 2016年08月11日 星期四 12时38分35秒
 ************************************************************************/

#include<iostream>
using namespace std;
class A
 {
    public:
            int a;
};

class B : public A 
{
};

class C : public A 
{
};

class D : public B, public C 
{
};

int main()
{
    D d;
    d.a = 1;
    return 0;
}

编译错误

dotheright@dotheright:~/mylovelycodes/cpp/base/9$
g++ muti_inherit.cpp
muti_inherit.cpp: In function ‘int main()’:
muti_inherit.cpp:31:4: error: request for member ‘a’ is ambiguous
d.a = 1;
^
muti_inherit.cpp:13:6: note: candidates are: int A::a
int a;
^
muti_inherit.cpp:13:6: note: int A::a

这里出现的错误是d.a 有二义性,这时候我们就要找二义分别是指的什么?
变量a的一种继承关系

Created with Raphaël 2.1.0 D D B B A A 继承于 继承于

变量a的另一种继承关系

Created with Raphaël 2.1.0 D D C C A A 继承于 继承于

A 由两份copy 所以会有二义性,消除二义性就是A只留一份,需要用到虚继承

/*************************************************************************
    > File Name: muti_inherit.cpp
    > Author: guoqingyao
    > Mail: stepbystepto@163.com 
    > Created Time: 2016年08月11日 星期四 12时38分35秒
 ************************************************************************/

#include<iostream>
using namespace std;
class A
{
public:
    int a;
};

class B :virtual public A 
{
};

class C :virtual public A 
{
};

class D : public B, public C
{
};

int main()
{
    D d;
    d.a = 1;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值