13.4 多重繼承與虛繼承(is-a)
虛擬繼承是多重繼承中特有的概念。虛擬基類是爲解決多重繼承而出現的。如:類D繼承自類B1、B2,而類B1、B2都繼承自類A,因此在類D中兩次出現類A中的變量和函數。爲了節省內存空間,可以將B1、B2對A的繼承定義爲虛擬繼承,而A就成了虛擬基類。實現的代碼如下:class A
class B1:public virtual A;
class B2:public virtual A;
class D:public B1,public B2;
#include<iostream>
#include<string>
using namespace std;
class Goods
{
double m_price;
int m_weight;
public:
Goods(double price,int weight):m_price(price),m_weight(weight){cout<< "Goods構造"<< endl;};
~Goods(){cout << "Goods析構"<<endl;};
void show(){cout << "價格是:" << m_price <<endl << "重量是:"<< m_weight<< endl;}
double getprice(){return m_price;};
};
class Camera : virtual public Goods //虛繼承
{
protected:
string m_type;
public:
Camera(double price,int weight,string type):Goods(price,weight),m_type(type)
{
cout << "Camera構造!" << endl;
};
~Camera()
{
cout << "Camera析構!" << endl;
};
void take(const char *obj)
{
cout << "給" << obj << "照相"<< endl;
};
};
class Mp3: virtual public Goods //虛繼承
{
string m_band;
public:
Mp3(double price, int weight,string band):Goods(price,weight),m_band(band)
{
cout << "Mp3構造!" << endl;
};
~Mp3()
{
cout << "Mp3析構!" << endl;
};
void play(const char* songname)
{
cout << "正在播放" << songname<<endl;
};
};
class SmartPhone: public Camera,public Mp3//多重繼承&虛繼承 is-a
{
public:
SmartPhone(double price , int weight,string type,string band)
:Goods(price, weight),Camera(price ,weight,type),Mp3(price,weight,band)
{
cout << "SmatrPhone構造!" << endl;
};
~SmartPhone()
{
cout << "SmartPhone析構!" << endl;
};
void call(const char* who)
{
cout << "給"<<who<<"打電話!" <<endl;
};
};
int main()
{
SmartPhone sp(200,2,"單反","蘋果");
sp.show();
sp.take("tiger");
sp.call("家裏");
return 0;
}
輸出結果:
13.5 多重繼承變成組合方式(has-a)
class MordenPhone //組合方式 has-a
{
Goods g;
Camera c;
Mp3 m;
public:
MordenPhone(double price,int weight,string type,string band)
:g(price ,weight),c(price,weight,type),m(price,weight,band)
{
cout << "MordenPhone構造!" << endl;
};
~MordenPhone()
{
cout << "MordenPhone析構!" << endl;
};
double getprice()
{
return m.getprice();
};
};
int main()
{
MordenPhone mp(2000,3,"數碼","三星");
cout << "MordenPhone's price is" << mp.getprice() << endl;
}