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;
}