#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