c++,多继承造成的二义性及解决办法

#include <iostream>
using namespace std;
//-------------------------------
class A1{
public:
    int a;
public:
    void m();
};

void A1::m() {
    cout<<"A1::m():a="<<this->a<<endl;
}

//-------------------------------
class A2 {
public:
    int a;
    void m();
};

void A2::m() {
    cout<<"A2::m(),a="<<this->a<<endl;
}

//-------------------------------
class B :public A1, public A2{
public:
    void show();
};

void B::show()
{
    cout<<"A1::a="<<this->A1::a<<endl;
    cout<<"A2::a="<<this->A2::a<<endl;
}

//-------------------------------
void f1() {
    B b;    
    b.A1::a = 34;
    b.A2::a = 32432;
    
    b.A1::m();//这时不能用b.m(),具有歧义;
    b.A2::m();//用格式 b.A1::m(), b.A2::m()明确对象,消除歧义
    b.show();
}
int main() {
    f1();
    while(1);
    return 0;
}
/*测试结果:

A1::m():a=34
A2::m(),a=32432
A1::a=34
A2::a=32432

*/

上面是两个基类有同样名称和形式的函数,都被继承到了子类中。访问他们的时候,要加上作用域才能正确地访问。

进一步来看,如果两个类都从同一个类派生,并没有重写某些函数,再有一个子类继承了它们两个。[共同基类产生的二义性]

情况就和上面类似了。代码如下:

#include <iostream>
using namespace std;
#include <string>

class A
{
public:
    int m_ax;
    void show();

    A();
    A(int a);

};
A::A()
{

}
A::A(int val)
{
    this->m_ax = val;
}

void A::show()
{
    cout << "A::m_ax = "<<m_ax<<endl;
}
class B1: public A{

};
class B2: public A{

};
class C: public B1 ,public B2 {
public:
    int m_cx;
    void show();
};
void C::show()
{
    //cout<<"c::show: m_ax = "<<m_ax<<endl;// error C2385: 对“m_ax”的访问不明确
    cout<<"c::show: A::m_ax = "<<A::m_ax<<endl;
    cout<<"c::show: B::m_ax = "<<B1::m_ax<<endl;
    cout<<"c::show: B::m_ax = "<<B2::m_ax<<endl;
    //从A、B1、B2派生下来的函数以及变量,在类C里面都得以保存,并各自占各自的独立的空间。
    //eg:尽管m_ax最初源于A类,但是派生到C类里面的有三个不同的m_ax。对于方法,同理。
}
int main()
{
    C c1 ;
    c1.show();

    //c1.m_ax = 11;//error C2385: 对“m_ax”的访问不明确
    c1.B1::m_ax = 11 ;
    c1.B1::show();

    while(1);
    return 0 ;
}

专门解决共同基类产生的二义性的办法还有虚基派生

见另一篇:

  c++, 虚基派生 : 共同基类产生的二义性的解决办法
  http://www.cnblogs.com/mylinux/p/4096926.html

原文地址:https://www.cnblogs.com/mylinux/p/4094258.html