[C++_8]继承_2

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值