福建农林大学实验报告
实验5 派生类和继承(二)
一、实验目的和要求
(1)掌握派生类的声明与定义方法,进一步理解类的继承的概念,能够定义和使用类的继承关系。(2)熟悉公有派生和私有派生的访问特性。
(3)了解虚基类在解决二义性问题中的作用。
二、实验内容和原理
1、试写出所能想到的所有形状(包括二维的和三维的),生成一个形状层次类结构。生成的层次结构以Shape作为基类,并由此派生出TwoDimShape类和ThreeDimShape类。它们的派生类是不同形状类,定义层次结构中的每一个类,并用函数main()进行测试。
2、设计一个学生类CStudent。数据成员包括学生姓名,性别,年龄,学号,已修学分。成员函数包括输入输出或修改学生姓名、学号,增加已修学分。设计一个教师类CTeacher。数据成员包括教师姓名,性别,年龄,职称,担任课程。成员函数包括输入输出或修改教师姓名、年龄,更改职称等。以CStudent为基类派生子类CGraduateStudent。增加数据成员导师姓名、研究生已发表论文的数目;成员函数为增加已发表论文数目。最后,用函数main()函数进行测试。(提示:可为CStudent 类和CTeacher类创建一个公共基类)
三、实验环境
1. 硬件:PC机;
2. 软件:Windows操作系统、Visual C++ 6.0
四、算法描述及实验步骤
#include
const double PI=3.14;
class shape
{
public:shape(){};
double area()const{return 0.0;}
double bulk()const{return 0.0;}
};
class TwoDimShape:public shape
{};
class Circle:public TwoDimShape
{
public:
Circle(double myr){R=myr;}
double area()const{return PI*R*R;}
protected:
double R;
};
class ThreeDimShape:public shape
{};
class sphere:public ThreeDimShape
{
public:
sphere(double myw){R=myw;}
double bulk()const{return 4/3*PI*R*R*R;} protected:
double R;
};
int main()
{
shape sha;
double area;
double bulk;
Circle c(3.0);
area=c.area();
cout<<"Area of circle is"<
bulk=sph.bulk();
cout<<"Bulk of sphere is"< return 0; } 2. #include #include using namespace std; class Person { public: Person(string n,string s,int a) {name=n;sex=s;age=a;} void input() { cin>>"姓名:">>name; cin>>"性别:">>sex; cin>>"年龄:">>age; } void display() { cout<<"姓名:"< cout<<"性别:"< cout<<"年龄:"< } protected: string name; int age; }; class Teacher:virtual public Person { public: Teacher(string n,string s,int a,string t,string l) :Person(n,s,a) { title=t; lesson=l; } void input() { Person::input(); cin>>"职称:">>title; cin>>"担任课程:">>lesson; } void display() { Person::display(); cout<<"职称:"< cout<<"担任课程:"< } protected: string title; string lesson; }; class Student:virtual public Person { public: Student(string n,string s,int a, string no,string c) :Person(n,s,a) { num=no; credit=c; } void input() { Person::input(); cin>>"学号:">>num; cin>>"已修学分:">>credit; } void display() Person::display(); cout<<"学号:"< cout<<"已修学分:"< } protected: string num; string credit; }; class Graduate:public Student { public: Graduate(string n,string s,int a,string no,string c,string tn,string th) :Person(n,s,a),Student(n,s,a,no,c) { tname=tn; thesis=th; } void input() { Person::input(); cin>>"导师姓名:">>tname; cin>>"发表论文数目:">>thesis; } void display() { Student::display(); cout<<"导师姓名:"< cout<<"发表论文数目:"< } private: string tname; string thesis; }; int main() { Teacher teac("镇镇","男",30,"博士","面向对象程序设计"); Student stud("星星","女",19,"100202019","6"); Graduate grad("杰杰","男",25,"100202021","18","源源","20"); cout<<"教师有关数据:"< teac.display(); cout<<"\n学生数据:"< stud.display(); cout<<"\n研究生数据:"< return 0; } 五、调试过程 PI=3.14后面忘记加“;”号了 return0.0应该是 return 0.0 protected 后面加的是:而不是; 2. 错误N多。。。 六、实验结果 七、总结 (1)掌握派生类的声明与定义方法,进一步理解类的继承的概念。(2)熟悉公有派生和私有派生的访问特性。 (3)写程序真麻烦老是错误N多。