C++多继承(多重继承)详解(二)命名冲突
生活随笔
收集整理的這篇文章主要介紹了
C++多继承(多重继承)详解(二)命名冲突
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
命名沖突
當(dāng)兩個或多個基類中有同名的成員時,如果直接訪問該成員,就會產(chǎn)生命名沖突,編譯器不知道使用哪個基類的成員。這個時候需要在成員名字前面加上類名和域解析符::,以顯式地指明到底使用哪個類的成員,消除二義性。
#include <iostream> using namespace std; //基類 class BaseA{ public:BaseA(int a, int b);~BaseA(); public:void show(); protected:int m_a;int m_b; }; BaseA::BaseA(int a, int b): m_a(a), m_b(b){cout<<"BaseA constructor"<<endl; } BaseA::~BaseA(){cout<<"BaseA destructor"<<endl; } void BaseA::show(){cout<<"m_a = "<<m_a<<endl;cout<<"m_b = "<<m_b<<endl; } //基類 class BaseB{ public:BaseB(int c, int d);~BaseB();void show(); protected:int m_c;int m_d; }; BaseB::BaseB(int c, int d): m_c(c), m_d(d){cout<<"BaseB constructor"<<endl; } BaseB::~BaseB(){cout<<"BaseB destructor"<<endl; } void BaseB::show(){cout<<"m_c = "<<m_c<<endl;cout<<"m_d = "<<m_d<<endl; }//派生類class Derived:public BaseA,public BaseB{public:Derived(int a ,int b,int c,int d,int e);~Derived();public:void display();private:int m_e;};Derived::Derived(int a, int b, int c, int d, int e):BaseA(a,b),BaseB(c,d),m_e(e){cout<<"Derived constructor"<<endl; }Derived::~Derived(){cout<<"Derived destructor"<<endl; }void Derived::display() {BaseA::show(); //調(diào)用BaseA類的 show()函數(shù)BaseB::show(); //調(diào)用BaseA類的 show()函數(shù)cout<<"m_e = "<<m_e<<endl; }int main(){Derived obj(1, 2, 3, 4, 5);obj.display();return 0; } 請讀者注意第 64、65 行代碼,我們顯式的指明了要調(diào)用哪個基類的 show() 函數(shù)。 《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的C++多继承(多重继承)详解(二)命名冲突的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++多继承(多重继承)详解(一)
- 下一篇: C++多继承时的对象内存模型