« | August 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | | | | | |
|
公告 |
My blog is about my major : network security.the most papers are talk about it ,I like my major ,i wish you could find what's you need in it. |
统计 |
blog名称:我的IT人生 日志总数:78 评论数量:185 留言数量:-1 访问次数:523933 建立时间:2006年4月5日 |
| 
|
本站首页 管理页面 写新日志 退出
[C/C++]C++类的多重继承与虚拟继承 |
设计如下的类的关系代码:
其中交通工具类vehicle具有属性:重量,函数setweight();showme();vehicle()构造函数;
小汽车类car具有属性:重量、排气量;函数setweight();showme();car()构造函数;
小船类boat具有自己的属性:重量、排水量;函数setweight();showme();boat()构造函数;
水陆两用汽车类amphibiancar具有属性:重量、排气量、排水量。函数setweight();showme();amphibiancar()构造函数;
鉴于以上特点,可以采用如下继承关系图来描述这4个类之间的关系:
500)this.width=500'>
vehicle类拥有成员变量 重量weight 和成员函数setweight();showme();vehicle();
其中showme()函数由于需要子函数进行重新定义,并且自身无法定义,所以设置为纯虚函数:virtual void ShowMe() = 0;具体由派生类自行定义实现。而setweight()函数由于所有的子类均能够完全调用而无须定义为虚函数;
Car类public继承vehicle类实现,并添加自身的属性 排气量aird,以及实现自身的showme函数。
Boat类public继承vehicle类实现,并添加自身的属性 吨位 tonnage,以及实现自身的showme函数。
Amphibiancar类继承car类和boat类,这样amphibiancar类的实际结构如下:
成员变量: Weight aird tonnage
成员函数:Amphibiancar car::setweight boat::setweight showme
即:
500)this.width=500'>
可以看到此时内存中会为Amphibiancar类初始化两个setweight函数,而实际上这两个函数是一样的,这时候需要把将car和boat类的继承方式申明为class Boat:virtual public Vehicle 和 class Car:virtual public Vehicle。(注意:虚类 和 虚函数 的意义完全不一样。)
具体实现如下:
#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"); }
参考文章:http://www.ttadd.com/diannao/HTML/29266.html
|
阅读全文(1544) | 回复(0) | 编辑 | 精华 |
|