当前位置:文档之家› 类的继承、派生、多态性C++课程实验报告

类的继承、派生、多态性C++课程实验报告

virtual void Stop(){cout<<"A vehicle is stopping!"<<endl;}
};
/*bicycle类与下面motorcar类虚拟继承vehicle类*/
class bicycle:virtual public vehicle
{
public:
void Run(){cout<<"A bicycle is running!"<<endl;}
3,主函数:申明基类指针,通过基类指针指向派生类指针来实现多态性和动态绑定。
实验内容
实验程序设计如下:
#include<iostream>
using namespace std;
/*定义vehicle类*/
class vehicle
{
public:
virtual void Run(){cout<<"A vehicle is running!"<<endl;}
void Stop(){cout<<"A bicycle is stopping!"<<endl;}
};
class motorcar:virtual public vehicle
{
public:
void Run(){cout<<"A motorcar is running!"<<endl;}
void Stop(){cout<<"A motorcar is stopping!"<<endl;}
ptr=&a3;
display(ptr);
ptr=&a4;
display(ptr);
a1.Run();
a2.Run();
a3.Run();
a4.Run();
return 0;
}
实验结果如图:
实验心得:通过这次实验,我掌握了类的继承与派生,学会类的虚拟继承避免多重派生的歧义性,还掌握乐通过虚函数实现多态性的方法。并且了解了动态绑定的技术。在实验过程中,开始出现了错误,后来把bicycle和motorcar类改为了虚拟继承,问题就解决了。
(1)建立如下几个类,关系满足如图
(2)具体要求
1,bicycle和motorcar虚拟继承于vehicle;
2,vehicle中申明数据成员表示:最高时速和重量;成员函数:Run和Stop用于实现车辆的启动和停止,这两个函数申明为虚拟函数;
3,bicycle、motorcar和motorcycle重载虚函数Run和Stop
这个实验让我对实现动态绑定的技术有了更多的了解。
教师签字
签字日期
2011年6月20
};
void display(vehicle *pp)
{
pp->Run();
pp->Stop();
}
int main(void)
{
vehicle a1,*ptr;
bicycle a2;
motorcar a3;
motorcycle a4;
ptr=&a1;
display(ptr);
ptr=&a2;
display(ptr);
};
/*motorcycle类的定义*/
class motorcycle: public bicycle,public motorcar
{
public:
void Run(){cout<<"A motorcycle is running!"<<endl;}
void Stop(){cout<<"A motorcycle is stopping!"<<endl;}
C++第五次实验
学生姓名
xxx
班级
雷电091
学号
xxxxxxxxxx
实验项目
实验五类继承、派生、多态性
指导的
(1)掌握类的继承与派生;
(2)学会类的虚拟继承避免多重派生的歧义性;
(3)掌握通过虚函数实现多态性的方法;
(4)掌握动态绑定的技术。
二、实验内容
编写如下要求的完整程序:动态绑定
相关主题