C++类的继承与派生 实验报告Word文档格式.docx
《C++类的继承与派生 实验报告Word文档格式.docx》由会员分享,可在线阅读,更多相关《C++类的继承与派生 实验报告Word文档格式.docx(12页珍藏版)》请在冰点文库上搜索。
![C++类的继承与派生 实验报告Word文档格式.docx](https://file1.bingdoc.com/fileroot1/2023-5/6/48afeff8-119d-4eb3-8389-2ff9a9dbd1b6/48afeff8-119d-4eb3-8389-2ff9a9dbd1b61.gif)
4、理解虚基类的目的和作用。
二.实验内容
(-)实验题目一:
声明一个圆类作为基类,含成员数据半径R;
有成员函数:
构造函数实现对基类成员数据的初始化、计算圆面积的成员函数、输出的成员函数,要求输出圆半径R。
把圆类作为基类,通过公有继承,派生圆柱体类,派生类新增成员数据有高(H);
新增成员函数有构造函数、计算圆柱体体积的函数、输出所有成员的函数。
main()完成派生类对象的定义和相关函数的测试。
2.程序源代码:
#include<
iostream>
usingnamespacestd;
classround
{
public:
round(floatm)
{
rad=m;
}
floatspace()
sp=3.14*rad*rad;
returnsp;
voiddisplay()
cout<
<
"
theroundofinformation"
endl;
该圆半径:
"
rad<
该圆面积:
space()<
protected:
floatrad;
floatsp;
};
classcylinder:
publicround
cylinder(floatm,floatn):
round(m)
high=n;
voidgethigh(floatn)
floatroom()
bulk=3.14*rad*rad*high;
returnbulk;
voidplay()
thecylinderofinformation:
该圆柱高:
high<
该圆柱体积:
room()<
floathigh;
floatbulk;
intmain()
floatm,n;
输入该圆半径:
;
cin>
>
m;
输入该圆柱高:
n;
cylinderss(m,n);
ss.display();
ss.play();
}
3.实验结果:
(二)实验题目二:
声明一个学生类,有成员函数:
学号、姓名、性别、年龄,要求有如下成员函数:
构造函数,输出所有成员的函数。
声明一个课程类,有成员数据:
课程编号、课程名称、学时数,要求有如下成员函数:
构造函数,输出所有成员的函数。
将学生类和课程类作为基类,通过公有继承,派生选课类,派生类新增成员数据有:
成绩;
新成员函数有:
main()完成派生类对象的定义和相关函数的测试。
string>
classstudent//student的类
student()//student默认构造函数
}
voidset1(char*n,char*id,char*s,inty)
name=n;
ID=id;
sex=s;
year=y;
voidget1()
name:
name<
cout<
ID:
ID<
sex:
sex<
theageis:
year<
stringname;
stringID;
stringsex;
intyear;
classsubject//subject类
subject()
voidset2(intsi,char*sn,intst)
subid=si;
subname=sn;
subtime=st;
voidget2()
thecoursename:
subname<
thecourseID:
subid<
thecourse'
stimeis:
subtime<
intsubid;
stringsubname;
intsubtime;
classssubject:
publicstudent,publicsubject
/*ssubject():
student(),subject()
}*/
voidset3(intsc)
score=sc;
voidget3()
sscoreis"
score<
intscore;
};
voidmain()
students;
s.set1("
liuguanhua"
"
20120040157"
nan"
20);
s.get1();
subjectss;
ss.set2(1,"
shuxue"
48);
ss.get2();
ssubjectsss;
sss.set1("
fuzizhou"
201200403152"
21);
sss.set2(1,"
sss.set3(80);
sss.get1();
sss.get2();
sss.get3();
3.实验结果
(三)实验题目三:
设计一个汽车类Vehicle,包含数据成员车轮和重量,由它派生出类Car和类Truck,前者包含载客数,后者包含载重量。
编写程序实现。
1.程序源代码:
classvehicle
voidget(intwe,intwh)
weight=we;
wheel=wh;
theweightis"
weight<
thewheelis"
wheel<
intweight;
intwheel;
classcar:
publicvehicle
public:
voidget1(intm)
busload=m;
voidplay1()
thebusloadis"
busload<
intbusload;
classtruck:
voidget2(intm)
deadweight=m;
voidplay2()
thedeadweightis"
deadweight<
intdeadweight;
vehicles;
carss;
trucksss;
s.get(3,5);
ss.get1(4);
sss.get2(10);
s.display();
ss.play1();
sss.play2();
2.实验结果
三.个人小结
通过此次实验,我掌握了利用单继承和多继承的方式定义派生类的方法。
理解在各种继承方式下构造函数和析构函数的执行顺序。
理解和掌握公有继承、私有继承和保护继承对基类成员的访问机制理解虚基类的目的和作用,对C++编程有了更进一步的理解!