1、1、声明一个抽象类shape,派生出rectangle和circle类,二者都有geta()和getb()函数,可分别计算出对象的面积和周长。2、设计一个类系统,其中有教师和学生,他们之前有相同的地方,也有自己的特征,利用继承机制定义这个类系统中各个类及类中必须的操作。三、实验结果及其结果分析#includeclass Shape /抽象类的 定义public: virtual double Geta() = 0; /纯虚函数 virtual double Getb() = 0;class Rectangle : public Shape /矩形类,公有继承 public: Rectangle
2、(double aa, double bb) /带参数的 构造函数 a=aa; b=bb; cout长a宽bendl; virtual double Geta() return a * b; virtual double Getb() return 2*( a + b ); private: double a; double b;class Circle : public Shape /圆类,公有继承 Circle(double rr) /带参数的 构造函数 r=rr;半径r return r * r * 3.14; virtual double Getb() return 2 * r * 3
3、.14;private: double r; void main() double length, width; cout length width; Rectangle rect(length, width);面积是: rect.Geta() endl周长是:rect.Getb() double rr;输入半径: rr; Circle cir(rr);cir.Geta() cir.Getb()2、#includestringusing namespace std;class Person Person(string n,string s,int a) name=n;sex=s;age=a;
4、void input() cin姓名:name;性别:sex;年龄:age; void display() namesexage职称:title;担任课程:lesson;display();titlelesson string title; string lesson;class Student:virtual public Person Student(string n,string s,int a, string no,string c):Person(n,s,a) num=no; credit=c; void input() 学号:num;已修学分:credit; void displa
5、y()numcredit string num; string credit;class Graduate:public Student 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() 导师姓名:tname;发表论文数目:thesis; Student:tnamethesis string tname; string thesis;int main() Teacher teac(镇镇,男,30,博士面向对象程序设计); Student stud(星星女,19,1002020196 Graduate grad(杰杰,25,10020202118源源20教师有关数据: teac.display();n学生数据: stud.display();n研究生数据: grad.display(); return 0;四、实验收获与体会 通过这次实验,我们复习了跟类有关的程序,自己能够掌握知识,去编写一个需要的程序。任何知识的学习,都要求我们能够融会贯通,学以致用。
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1