C 多态性实验报告含代码和结果截图.doc
文本预览下载声明
PAGE 3
实验报告
课程:
面向对象技术
学号:
姓名:
班级:
教师:
计算机科学与技术系
实验六 多态性
一、实验目的及要求
1.掌握运算符重载的方法;
2.掌握使用虚函数实现动态多态性。
二、实验环境
硬件:计算机 软件:Microsoft Visual C++
三、实验内容
声明一个车(vehicle)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数。观察虚函数的作用。
四、实验结果(附截图)
五、总结
通过本次实验,我对虚函数、多态性有了进一步了解,对多态性也有了更深的认识,实验中还是有很多的问题不是很清楚,平时要认真学习好理论知识,这样才能在做实验时更好的理解代码,才能更快的改正自己调试时遇到的错误。
六、附录(源程序清单)
#includeiostream
using namespace std;
int sign=0;
class vehicle
{
public:
vehicle(float m,float w)
{
if(m240m0)
MaxSpeed=m;
else
{
cout汽车超速!endl;
sign=1;
return;
}
if(w500w0)
Weight=w;
else
{
cout汽车超重!endl;
sign=1;
return;
}
cout构造了一个vehicle对象endl;
}
virtual void Run() { coutvehicle Run 函数被调用endl;}
virtual void Stop(){ coutvehicle Stop 函数被调用endlendl;}
private:
float MaxSpeed;
float Weight;
}
class bicycle:virtual public vehicle
{
public:
bicycle(float h,float m,float w):vehicle(m,w)
{
if(h1.5h0)
Height=h;
else
{
cout自行车超高!endl;
sign=1;
return;
}
cout构造了一个bicycle对象endl;
}
void Run() { coutbicycle Run 函数被调用endl;}
void Stop(){ coutbicycle Stop 函数被调用endlendl;}
private:
float Height;
}
class motorcar:virtual public vehicle
{
public:
motorcar(float s,float m,float w):vehicle(m,w)
{
if(s2s0)
SeatNum=s;
else
{
cout摩托车超载!endl;
sign=1;
return;
}
cout构造了一个motorcar对象endl;
}
void Run() { coutmotorcar Run 函数被调用endl;}
void Stop(){ coutmotorcar Stop 函数被调用endlendl;}
private:
float SeatNum;
}
class motorcycle:public bicycle,public motorcar
{
public:
motorcycle(float h,float s,float m,float w):bicycle(h,m,w),motorcar(s,m,w),vehicle(m,w)
{
if(sign==0)
{
cout构造了一个motorcycle对象endl;
}
}
void Run() { coutmotorcycle Run 函数被调用endl;}
void Stop(){ coutmotorcycle Stop 函数被调用endlendl;}
};
void main ()
{
float m,w,h,s;
int p;
do{
sign=0;
cout请输入参数:endlendl;
cout汽车最高时速(km/h);
cinm;
cout汽车重量(t);
cinw;
cout自行车高度(m);
cinh;
cout摩托
显示全部