多繼承容易讓代碼邏輯復雜、思路混亂,一直備受爭議,中小型項目中較少使用,後來的 Java、C#、PHP 等干脆取消了多繼承。想快速學習C++的讀者可以不必細讀。多繼承的語法也很簡單,將多個基類用逗號隔開即可。例如已聲明了類A、類B和類C,那麼可以這樣來聲明派生類D:
class D: public A, private B, protected C{
//類D新增加的成員
}
D(形參列表): A(實參列表), B(實參列表), C(實參列表){
//其他操作
}
D(形參列表): B(實參列表), C(實參列表), A(實參列表){
//其他操作
}
#include <iostream> using namespace std; //基類 class BaseA{ public: BaseA(int a, int b); ~BaseA(); 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; } //基類 class BaseB{ public: BaseB(int c, int d); ~BaseB(); 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; } //派生類 class Derived: public BaseA, public BaseB{ public: Derived(int a, int b, int c, int d, int e); ~Derived(); public: void show(); 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::show(){ cout<<m_a<<", "<<m_b<<", "<<m_c<<", "<<m_d<<", "<<m_e<<endl; } int main(){ Derived obj(1, 2, 3, 4, 5); obj.show(); return 0; }運行結果:
::
,以顯式地指明到底使用哪個類的成員,消除二義性。#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(); //調用BaseA類的show()函數 BaseB::show(); //調用BaseB類的show()函數 cout<<"m_e = "<<m_e<<endl; } int main(){ Derived obj(1, 2, 3, 4, 5); obj.display(); return 0; }請讀者注意第 64、65 行代碼,我們顯式的指明了要調用哪個基類的 show() 函數。