Chinaunix首页 | 论坛 | 博客
  • 博客访问: 58885
  • 博文数量: 29
  • 博客积分: 667
  • 博客等级: 上士
  • 技术积分: 300
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-11 15:55
文章分类
文章存档

2012年(2)

2011年(27)

我的朋友
最近访客

分类: C/C++

2011-10-31 10:48:12

  1. #include <iostream>

  2. using namespace std;

  3.   
  4. class Vehicle

  5. {

  6.     public:

  7.         Vehicle(int weight = 0)

  8.         {

  9.             Vehicle::weight = weight;

  10.             cout<<"载入Vehicle类构造函数"<<endl;

  11.         }

  12.         void SetWeight(int weight)

  13.         {

  14.             cout<<"重新设置重量"<<endl;

  15.             Vehicle::weight = weight;

  16.         }

  17.         virtual void ShowMe() = 0;

  18.     protected:

  19.         int weight;

  20. };

  21. class Car:virtual public Vehicle//汽车,这里是虚拟继承

  22. {

  23.     public:

  24.         Car(int weight=0,int aird=0):Vehicle(weight)

  25.         {

  26.             Car::aird = aird;

  27.             cout<<"载入Car类构造函数"<<endl;

  28.         }

  29.         void ShowMe()

  30.         {

  31.             cout<<"我是汽车!"<<endl;

  32.         }

  33.     protected:

  34.         int aird;

  35. };

  36.   

  37. class Boat:virtual public Vehicle//,这里是虚拟继承

  38. {

  39.     public:

  40.         Boat(int weight=0,float tonnage=0):Vehicle(weight)

  41.         {

  42.             Boat::tonnage = tonnage;

  43.             cout<<"载入Boat类构造函数"<<endl;

  44.         }

  45.         void ShowMe()

  46.         {

  47.             cout<<"我是船!"<<endl;

  48.         }

  49.     protected:

  50.         float tonnage;

  51. };

  52.   

  53. class AmphibianCar:public Car,public Boat//水陆两用汽车,多重继承的体现

  54. {

  55.     public:

  56.         AmphibianCar(int weight,int aird,float tonnage)

  57.         :Vehicle(weight),Car(weight,aird),Boat(weight,tonnage)

  58.         //多重继承要注意调用基类构造函数

  59.         {

  60.             cout<<"载入AmphibianCar类构造函数"<<endl;

  61.         }

  62.         void ShowMe()

  63.         {

  64.             cout<<"我是水陆两用汽车!"<<endl;

  65.         }

  66.         void ShowMembers()

  67.         {

  68.             cout<<"重量:"<<weight<<"吨,"<<"空气排量:"<<aird<<"CC,"<<"排水量:"<<tonnage<<"吨"<<endl;

  69.         }

  70. };

  71. int main()

  72. {

  73.     AmphibianCar a(4,200,1.35f);

  74.     a.ShowMe();

  75.     a.ShowMembers();

  76.     a.SetWeight(3);

  77.     a.ShowMembers();

  78.     cout << sizeof(Vehicle ) << endl;

  79.     cout << sizeof(Car ) << endl;

  80.     cout << sizeof(Boat) << endl;

  81.     cout << sizeof(AmphibianCar) << endl;

  82. }

/*
我们在Car类和Boat类继承Vehicle类时,在前面加上virtual关键字就可以实现虚拟继承,使用虚拟继承后,当系统碰到多重继承的时候就会自动先加入一个Vehicle的拷贝,当再次请求一个Vehicle的拷贝的时候就会被忽略,保证继承类成员函数的唯一性。
*/
 
载入Vehicle类构造函数
载入Car类构造函数
载入Boat类构造函数
载入AmphibianCar类构造函数
我是水陆两用汽车!
重量:4吨,空气排量:200CC,排水量:1.35吨
重新设置重量
重量:3吨,空气排量:200CC,排水量:1.35吨


阅读(448) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~