在多重继承中,当在派生类中出现两个以上同名的可直接访问的基类成员时,会出现二义性,也称为访问冲突。
#include <iostream>
using namespace std;
class A
{
protected:
int x;
public:
A(int a=0)
{
x = a;
cout << "A Constructor" << endl;
}
~A()
{
cout << "A Destructor" << endl;
}
};
class B
{
protected:
int x;
public:
B(int a=0)
{
x= a;
cout << x << ", B Constructor" << endl;
}
~B()
{
cout << x << ", B Destructor" << endl;
}
};
class C: public A, public B
{
int data3, data4;
B bdata;
public:
C(int a1=0, int a2=0, int a3=0, int a4=0): bdata(a1), A(a1), B(a2)
{
data3 = a3;
data4 = a4;
cout << "C Constructor" << endl;
}
~C()
{
cout << "C Destructor" << endl;
}
void show()
{
cout << A::x << ',' << B::x << ',' << data3 << ',' << data4 << endl;
}
};
int main()
{
C c(1,2,3,4);
c.show();
return 0;
}
基类A和基类B中均有变量名为 x 的数据成员,在派生类C的成员函数show()中,根据 A::x 和 B::x 来解决二义性。(作用域运算符不能嵌套使用,即C::A::x)