//程式作者:管寧
//網站:www.cndev-lab.com
//所有稿件均有著作權,如要轉載,請務必著名出處和作者
#include "stdafx.h"
#include <iostream>
using namespace std;
class Vehicle
...{
public:
Vehicle(int weight = 0)
...{
Vehicle::weight = weight;
cout<<"載入Vehicle類建構函式"<<endl;
}
void SetWeight(int weight)
...{
cout<<"重新設定重量"<<endl;
Vehicle::weight = weight;
}
virtual void ShowMe() = 0;
protected:
int weight;
};
class Car:virtual public Vehicle//汽車,這裡是虛擬繼承
...{
public:
Car(int weight=0,int aird=0):Vehicle(weight)
...{
Car::aird = aird;
cout<<"載入Car類建構函式"<<endl;
}
void ShowMe()
...{
cout<<"我是汽車!"<<endl;
}
protected:
int aird;
};
class Boat:virtual public Vehicle//船,這裡是虛擬繼承
...{
public:
Boat(int weight=0,float tonnage=0):Vehicle(weight)
...{
Boat::tonnage = tonnage;
cout<<"載入Boat類建構函式"<<endl;
}
void ShowMe()
...{
cout<<"我是船!"<<endl;
}
protected:
float tonnage;
};
class AmphibianCar:public Car,public Boat//水陸兩用汽車,多重繼承的體現
...{
public:
AmphibianCar(int weight,int aird,float tonnage)
:Vehicle(weight),Car(weight,aird),Boat(weight,tonnage)
//多重繼承要注意調用基類建構函式
...{
cout<<"載入AmphibianCar類建構函式"<<endl;
}
void ShowMe()
...{
cout<<"我是水陸兩用汽車!"<<endl;
}
void ShowMembers()
...{
cout<<"重量:"<<weight<<"頓,"<<"空氣排量:"<<aird<<"CC,"<<"排水量:"<<tonnage<<"頓"<<endl;
}
};
int main()
...{
AmphibianCar a(4,200,1.35f);
a.ShowMe();
a.ShowMembers();
a.SetWeight(3);
a.ShowMembers();
system("pause");
}
在圖中深紅色標記出來的地方正是主要問題所在,水陸兩用汽車類繼承了來自Car類與Boat類的屬性與方法,Car類與Boat類同為AmphibianCar類的基類,在記憶體配置上AmphibianCar獲得了來自兩個類的SetWeight()成員函數,當我們調用a.SetWeight(3)的時候電腦不知道如何選擇分別屬於兩個基類的被重複擁有了的類成員函數SetWeight()。
由於這種模糊問題的存在同樣也導致了AmphibianCar a(4,200,1.35f);執行失敗,系統會產生Vehicle”不是基或成員的錯誤。
以上面的代碼為例,我們要想讓AmphibianCar類既獲得一個Vehicle的拷貝,而且又同時共用用Car類與Boat類的資料成員與成員函數就必須通過C++所提供的虛擬繼承技術來實現。
我們在Car類和Boat類繼承Vehicle類出,在前面加上virtual關鍵字就可以實現虛擬繼承,使用虛擬繼承後,當系統碰到多重繼承的時候就會自動先加入一個Vehicle的拷貝,當再次請求一個Vehicle的拷貝的時候就會被忽略,保證繼承類成員函數的唯一性。