1. 程式人生 > 其它 >c++——菱形繼承

c++——菱形繼承

技術標籤:c++繼承

1. 概念

A作為基類,B、C繼承於A。類D繼承於B、C,這樣形式的繼承稱為菱形繼承。

2. 示意圖

3. 缺點

1)資料冗餘:在D中會儲存兩份A的內容;

2)訪問不明確(二義性):因為D不知道是以B為中介去訪問A還是以C為中介去訪問A,因此在訪問某些成員的時候會發生二義性;

4. 解決方案

1)通過虛繼承的方式解決;

2)通過作用域訪問符“::”來明確呼叫;

5. 示例

class ProductA
{
public:
	ProductA(int a) :m_iNumA(a) {}
	int getNum() const { return m_iNumA; }
private:
	int m_iNumA;
};

class ProductB : public ProductA
{
public:
	ProductB(int a, int b) :ProductA(a), m_iNumB(b) {}
private:
	int m_iNumB;
};

class ProductC : public ProductA
{
public:
	ProductC(int a, int b) :ProductA(a), m_iNumC(b) {}
private:
	int m_iNumC;
};

class ProductD :public ProductB, public ProductC
{
public:
	ProductD(int a, int b, int c, int d) : ProductB(a, b), ProductC(a, c), m_iNumD(d) {}
	void func()
	{
		//錯誤,訪問不明確
		//cout << getNum()<<endl;

		//正確,通過B訪問getMa()
		cout << ProductB::getNum() << endl;
		cout << ProductC::getNum() << endl;
	}
private:
	int m_iNumD;
};