实验六 多态性和虚函数
- 格式:docx
- 大小:13.40 KB
- 文档页数:2
C++多态性实验报告含代码和结果截图实验报告课程:面向对象技术学号:姓名:班级:教师:计算机科学与技术系实验六多态性一、实验目的及要求1.掌握运算符重载的方法;2.掌握使用虚函数实现动态多态性。
二、实验环境硬件:计算机软件:Microsoft Visual C++三、实验内容声明一个车(vehicle)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数。
观察虚函数的作用。
四、实验结果(附截图)五、总结通过本次实验,我对虚函数、多态性有了进一步了解,对多态性也有了更深的认识,实验中还是有很多的问题不是很清楚,平时要认真学习好理论知识,这样才能在做实验时更好的理解代码,才能更快的改正自己调试时遇到的错误。
六、附录(源程序清单)#includeusing namespace std;int sign=0;class vehicle{vehicle(float m,float w){if(m<240&&m>0)MaxSpeed=m;else{cout<<"汽车超速!"<<endl;< p="">sign=1;return;}if(w<500&&w>0)Weight=w;else{cout<<"汽车超重!"<<endl;< p="">sign=1;return;}cout<<"构造了一个vehicle对象"<<endl;< p="">}virtual void Run() { cout<<"vehicle Run 函数被调用"<<endl;}< p="">virtual void Stop(){ cout<<"vehicle Stop 函数被调用"<<endl<<="">float MaxSpeed;float Weight;}class bicycle:virtual public vehicle{public:bicycle(float h,float m,float w):vehicle(m,w){if(h<1.5&&h>0)Height=h;elsecout<<"自行车超高!"<<endl;< p="">sign=1;return;}cout<<"构造了一个bicycle对象"<<endl;< p="">}void Run() { cout<<"bicycle Run 函数被调用"<<endl;}< p=""> void Stop(){ cout<<"bicycle Stop 函数被调用"<<endl<<endl;}< p="">private:float Height;}class motorcar:virtual public vehicle{public:motorcar(float s,float m,float w):vehicle(m,w){if(s<2&&s>0)SeatNum=s;else{cout<<"摩托车超载!"<<endl;< p="">sign=1;return;}cout<<"构造了一个motorcar对象"<<endl;< p="">}void Run() { cout<<"motorcar Run 函数被调用"<<endl;}< p="">void Stop(){ cout<<"motorcar Stop 函数被调用"<<endl<<endl;}< p="">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),vehi cle(m,w){if(sign==0){cout<<"构造了一个motorcycle对象"<<endl;< p="">}}void Run() { cout<<"motorcycle Run 函数被调用"<<endl;}< p="">void Stop(){ cout<<"motorcycle Stop 函数被调用"<<endl<<endl;}< p="">};void main (){float m,w,h,s;int p;do{sign=0;cout<<"请输入参数:"<<endl<<endl;< p="">cout<<"汽车最高时速(km/h)";cin>>m;cout<<"汽车重量(t)";cin>>w;cout<<"自行车高度(m)";cin>>h;cout<<"摩托车座位(个)";cin>>s;motorcycle car(h,s,m,w);if(sign==0){car.Run();car.Stop();}else{cout<<"1—重新输入2——结束程序";cin>>p;if(p==2)return;elsecout<<endl<<endl;< p=""> }}while(sign==1);}</endl<<endl;<></endl<<endl;<></endl<<endl;}<></endl;}<></endl;<></endl<<endl;}<></endl;}<></endl;<></endl;<></endl<<endl;}<></endl;}<></endl;<></endl;<></endl<</endl;}<></endl;<></endl;<></endl;<>。
一.实验目的及要求1.进一步熟悉类的设计、运用继承与派生机制设计派生类,合理设置数据成员和成员函数。
2.掌握通过继承、虚函数、基类的指针或引用实现动态多态性的方法。
3.理解并掌握具有纯虚函数的抽象类的作用,在各派生类中重新定义各纯虚函数的方法,以及此时实现的动态多态性。
二.实验内容在自己的文件夹下建立一个名为exp5的工程,在该工程中做如下操作:定义一个抽象类容器类,其中定义了若干纯虚函数,实现求表面积、体积、输出等功能。
由此抽象类派生出正方体、球体和圆柱体等多个派生类,根据需要定义自己的成员变量,在各个派生类中重新定义各纯虚函数,实现各自类中相应功能,各个类成员的初始化均由本类构造函数实现。
(1)在主函数中,定义容器类的指针和各个派生类的对象,使指针指向不同对象处调用相同的函数能执行不同的函数代码,从而实现动态多态性。
(2)定义一个顶层函数void TopPrint(Container &r);使得主函数中调用该函数时,根据实在参数所有的类自动调用对应类的输出函数。
(3)主函数中定义一个Container类对象,观察编译时的错误信息,从而得出什么结论三.实验程序及运行结果#include <iostream>using namespace std;class Base{public:virtual void f(){ cout << "调用Base::f()" << endl; }};class Derived: public Base{public:void f(){ cout << "调用Derived::f()" << endl; } // 虚函数};int main(void){Derived obj; // 定义派生类对象Base *p = &obj; // 基类指针p->f(); // 调用函数f()system("PAUSE");return 0;}2.#include <iostream>using namespace std; //class Base{public:virtual void Show() const{ cout << "调用Base::Show()" << endl; } // 虚函数};class Derived: public Base{public:void Show() const{ cout << "调用Derived::Show()" << endl; }};void Refers(const Base &obj) // 基类引用{obj.Show(); // 调用函数Show()}int main(void){Base obj1;Derived obj2; // 定义对象Refers(obj1); // 调用函数Refers()Refers(obj2);system("PAUSE");return 0;}3.#include <iostream>using namespace std; /class Base{private:int m;public:Base(int a): m(a){ }virtual void Show() const{ cout << m << endl; }// 虚函数};class Derived: public Base{private:int n;public:Derived(int a, int b): Base(a), n(a){ } // 构造函数void Show() const{cout << n << ","; /Base::Show(); // 调用基类的Show() }};int main(void){Base obj1(168);Derived obj2(158, 98);Base *p;p = &obj1;p->Show();p = &obj2;p->Show();p->Base::Show();system("PAUSE");return 0;}4.#include <iostream>using namespace std;class A{public:virtual void Show() const{ cout << "基类A" << endl; } };class B: public A{public:void Show() const{ cout << "派生类B" << endl; } };int main(void){B obj;A *p = &obj;p->Show();system("PAUSE");return 0;}5.#include <iostream>using namespace std;const double PI = 3.1415926;class Shape{public:virtual void Show() const = 0;static double sum;};class Circle: public Shape{private:double radius;public:Circle(double r): radius(r){ sum += PI * radius * radius; }void Show() const{cout << "圆形:" << endl;cout << "半径:" << radius << endl;cout << "面积:" << PI * radius * radius << endl;}};class Rectangle: public Shape{private:double height;double width;public:Rectangle(double h, double w): height(h), width(w){ sum += height * width; }void Show() const{cout << "矩形:" << endl;cout << "高:" << height << endl;cout << "宽:" << width << endl;cout << "面积:" << height * width << endl;}};double Shape::sum = 0;int main(void){char flag = 'Y'; 'Shape *p;while (toupper(flag) == 'Y'){cout << "请选择输入类别(1.圆形2.矩形)";int select;cin >> select;switch (select){case 1:double r;cout << "输入半径:";cin >> r;p = new Circle(r);p->Show();delete p;break;case 2:double h, w;cout << "输入高:";cin >> h;cout << "输入宽:";cin >> w;p = new Rectangle(h, w);p->Show(); // 显示相关信息delete p; // 释放存储空间break;default: // 其它情况, 表示选择有误cout << "选择有误!"<< endl;break;}cout << endl << "是否继续录入信息?(Y/N)";cin >> flag;}cout << "总面积:" << Shape::sum << endl;system("PAUSE");return 0;}6.#include <iostream>using namespace std;const double PI = 3.1415926;const int NUM = 10;class Shape{public:virtual void ShowArea() const = 0;static double sum;};class Circle: public Shape{private:double radius;public:Circle(double r): radius(r){ sum += PI * radius * radius; }void ShowArea() const{ cout << "圆面积:" << PI * radius * radius << endl; }};class Rectangle: public Shape{private:double height;double width;public:Rectangle(double h, double w): height(h), width(w){ sum += height * width; }void ShowArea() const{ cout << "矩形面积:" << height * width << endl; }};class Square: public Shape{private:double length;public:Square(double a): length(a){ sum += length * length; }void ShowArea() const{ cout << "正方形面积:" <<length * length << endl; } };double Shape::sum = 0;int main(void){Shape *shape[NUM];int count = 0;while (count < NUM){cout << "请选择(1.圆形2.矩形3.正方形4.退出):";int select;cin >> select;if (select == 4) break;switch (select){case 1:double r;cout << "输入半径:";cin >> r;shape[count] = new Circle(r);shape[count]->ShowArea();count++;break;case 2:double h, w;cout << "输入高:";cin >> h;cout << "输入宽:";cin >> w;shape[count] = new Rectangle(h, w);shape[count]->ShowArea();count++;break;case 3:double a;cout << "输入边长:";cin >> a;shape[count] = new Square(a);shape[count]->ShowArea();count++;break;default:cout << "选择有误!"<< endl;break;}}cout << "总面积:" << Shape::sum << endl;for (int i = 0; i < count; i++) delete shape[i];system("PAUSE");return 0;}五.实验总结通过本次试验 我更深刻的理解了某些语句如何使用及结构体的优点 也能更加熟练的编写简单的程序了 我深知实践要比书本更加重要 今后还要多练习 在实践中学习。
实验6 多态性与虚函数
实验6 多态性与虚函数
6.1 实验目的
1 .理解多态性的概念;
2 .掌握虚函数的作用及使用方法;
3 .了解静态关联和动态关联的概念和用法;
4 .了解纯虚函数和抽象类的概念和用法。
6.2 实验内容
程序设计部分
1 、定义平面图形的抽象基类figure,然后派生出四种几何图形是:三角形
/Triangle、矩形/Rectangle、正方形/Square和圆/Circle,利用基类指针和虚函数的多
态性来计算四种几何图形的面积和周长,这几何图形的参数通过构造函数来设置。
2 、定义立体图形的抽象基类shape,然后派生出:球、圆柱和圆锥,利用基类的引
用和虚函数的多态性来计算它们的表面积和体积。
本课程复习要点: 1、有关概念和知识点
变量的作用域和生存期,引用,常量,内联函数,函数重载,动态内存分配,输入/
输出流;类与对象,构造函数,拷贝构造函数,析构函数,友元;类成员的访问控制属性,this指针,静态成员,成员对象;派生/继承,多继承,构造函数调用顺序,虚基类;多态性与虚函数,抽象基类,运算符重载。
2、几个较完善的C++教学参考电子文档
3、练习:《C++程序设计基础与实践教程》习题解答、每个实验中的题目
感谢您的阅读,祝您生活愉快。
实验6 多态性与虚函数一.实验目的1.了解多态的概念;2.了解静态联编和动态联编的概念;3.掌握动态联编的条件;4.了解虚函数的用途及使用方法。
二源程序#include<iostream>using namespace std;class Shape{public:virtual double area()const=0;virtual void display()=0;};class TwoDimShape:public Shape{};class ThreeDimShape:public Shape{};class Circle:public TwoDimShape{public:Circle(double r){R=r;}double area()const{return 3.14*3.14*R;}void display(){cout<<"圆的面积为:"<<area()<<endl;}private:double R;};class Cube:public ThreeDimShape{public:Cube(double l){L=l;}double area()const{return 6*L*L;}void display(){cout<<"立方体的表面积为:"<<area()<<endl;} private:double L;};int main(){int i;Circle Ci1(5.2);Cube Cu1(3.3);Shape *S1[2]={&Ci1,&Cu1};for(i=0;i<2;i++){S1[i]->area();S1[i]->display();}return 0;}三.编程思想圆和立方体不属于同一类,这两类的参数不同计算方法不同,但是所求的都是面积输出的也都是面积这一个相同的成员函数。
实验六、多态性与虚函数09计算机1 白杨0929210028在掌握继承与派生的基础上,进一步理解多态性与虚函数的关系,实现运行时的多态性。
(1)通过定义形状类Shape,并派生出各类具体形状,标准模板库完成TOJ中的2034题:面积排序(2)分析该题目中所涉及的抽象类、虚函数等概念;(3)分析该题目特别要注意的地方。
Toj 2034#include<iostream>#include<vector>#include<string>#include<cmath>#include<iomanip>#include<algorithm>using namespace std;#define PI 3.1415926class Point{private:double x, y;public:Point() {}Point(double _x, double _y) : x(_x), y(_y) {}Point(const Point& P) {x = P.x; y = P.y;}~Point() {}void SetPoint() {cin>>x>>y;}friend class Triangle;friend class Rectangle;friend class Circle;};class Shape{public:string Sname;Shape() {}Shape(string name) {Sname = name;}Shape(const Shape& S) {Sname = S.Sname;}~Shape() {}virtual void Set(string name) {cin>>Sname;}virtual double Area() {return 0.0;}void Print() {cout.setf(ios::fixed); cout<<Sname<<" "<<setprecision(3)<<Area()<<endl;}};class Triangle : public Shape{private:Point p1, p2, p3;public:Triangle() {}Triangle(string name, Point _p1, Point _p2, Point _p3) : Shape(name), p1(_p1), p2(_p2), p3(_p3) {}Triangle(const Triangle& T) {Sname = T.Sname; p1 = T.p1; p2 = T.p2; p3 = T.p3;}~Triangle() {}void Set(string name) {Sname = name; p1.SetPoint(); p2.SetPoint(); p3.SetPoint();}double Area() {return fabs(p1.x*p2.y-p2.x*p1.y+p2.x*p3.y-p3.x*p2.y+p3.x*p1.y-p1.x*p3.y)*0.5;}};class Rectangle : public Shape{private:Point p1, p2;public:Rectangle() {}Rectangle(string name, Point _p1, Point _p2) : Shape(name), p1(_p1), p2(_p2) {}Rectangle(const Rectangle& R) {Sname = R.Sname; p1 = R.p1; p2 = R.p2;}~Rectangle() {}void Set(string name) {Sname = name; p1.SetPoint(); p2.SetPoint();}double Area() {return fabs(p1.x-p2.x)*fabs(p1.y-p2.y);}};class Circle : public Shape{private:Point center;double r;public:Circle() {}Circle(string name, Point _center, double _r) : Shape(name), center(_center), r(_r) {}Circle(const Circle& C) {Sname = C.Sname; center = C.center; r = C.r;}~Circle() {}void Set(string name) {Sname = name; center.SetPoint(); cin>>r;}double Area() {return PI*r*r;}};bool cmp(Shape* s1, Shape* s2){if(s1->Area() == s2->Area())return s1->Sname < s2->Sname;return s1->Area() > s2->Area();}int main(){vector<Shape *> s;Shape *tmp;string str;int t1(0), r1(0), c1(0);while(cin>>str){if(str=="triangle"){tmp = new Triangle;tmp->Set(str += ++t1+'0');}else if(str=="rectangle"){tmp = new Rectangle;tmp->Set(str += ++r1+'0');}else if(str=="circle"){tmp = new Circle;tmp->Set(str += ++c1+'0');}s.push_back(tmp);}sort(s.begin(),s.end(),cmp);vector<Shape *>::iterator i;for(i=s.begin();i!=s.end();i++)(*i)->Print();return 0;}总结:通过指向派生类对象的基类指针访问函数成员时:非虚函数由指针类型决定调用的版本虚函数由指针指向的实际对象决定调用的版本。
多态性与虚函数实验报告实验目的:通过实验掌握多态性和虚函数的概念及使用方法,理解多态性实现原理和虚函数的应用场景。
实验原理:1.多态性:多态性是指在面向对象编程中,同一种行为或者方法可以具有多种不同形态的能力。
它是面向对象编程的核心特性之一,能够提供更加灵活和可扩展的代码结构。
多态性主要通过继承和接口来实现。
继承是指子类可以重写父类的方法,实现自己的特定行为;接口是一种约束,定义了类应该实现的方法和属性。
2.虚函数:虚函数是在基类中声明的函数,它可以在派生类中被重新定义,以实现多态性。
在类的成员函数前面加上virtual关键字,就可以将它定义为虚函数。
当使用基类指针或引用调用虚函数时,实际调用的是派生类的重写函数。
实验步骤:1. 创建一个基类Shape,包含两个成员变量color和area,并声明一个虚函数printArea(用于打印面积。
2. 创建三个派生类Circle、Rectangle和Triangle,分别继承Shape类,并重写printArea(函数。
3. 在主函数中,通过基类指针分别指向派生类的对象,并调用printArea(函数,观察多态性的效果。
实验结果与分析:在实验中,通过创建Shape类和派生类Circle、Rectangle和Triangle,可以实现对不同形状图形面积的计算和打印。
当使用基类指针调用printArea(函数时,实际调用的是派生类的重写函数,而不是基类的函数。
这就是多态性的实现,通过基类指针或引用,能够调用不同对象的同名函数,实现了对不同对象的统一操作。
通过实验1.提高代码的可扩展性和灵活性:通过多态性,可以将一类具有相似功能的对象统一管理,节省了代码的重复编写和修改成本,增强了代码的可扩展性和灵活性。
2.简化代码结构:通过虚函数,可以将各个派生类的不同行为统一命名为同一个函数,简化了代码结构,提高了代码的可读性和维护性。
3.支持动态绑定:通过运行时的动态绑定,可以根据对象的实际类型来确定调用的函数,实现了动态绑定和多态性。
南阳理工学院C++上机实验指导书(2011版)软件学院·软件工程教研室2011.3C++上机实验指导书——软件学院·软件工程教研室[2011版]目录实验1 C++编程环境实践....................... 错误!未定义书签。
实验2 基本数据类型、运算符和表达式. (2)实验3 选择和循环结构(*)............... 错误!未定义书签。
实验4 指针与引用(*) ....................... 错误!未定义书签。
实验5 函数与重载.................................. 错误!未定义书签。
实验6 类与对象 ...................................... 错误!未定义书签。
实验7 运算符重载(*) ....................... 错误!未定义书签。
实验8 继承............................................... 错误!未定义书签。
实验9 多继承(*)................................ 错误!未定义书签。
实验10 多态与虚函数 (2)注:带“*”为选做实验,建议学生课后自行完成实验10 多态与虚函数一、实验目的1.理解多态的概念2.掌握如何用虚函数实现运行时多态3.掌握如何利用抽象类二、实验内容及步骤1.设计一个图形类(Shape),由它派生出5个派生类:三角形类(Triangle)、正方形类(Square)、圆形类(Circle)、矩形类(Rectangle)、梯形类(triangle)类,利用虚函数计算图形面积,用一个函数printArea分别输出以上5者的面积。
#include<iostream>#include<iomanip>#include<cmath>using namespace std;const double PI = 3.1415926;class Shape{public:virtual double GetArea() = 0;};class Triangle : public Shape{private:double a, b, c;public:double TArea;double GetArea();};double Triangle::GetArea(){cout << "请输入三角形的三边长: ";cin >> a >> b >> c;while((a < 0) || (b < 0) || (c < 0) || (a + b <= c) || (a + c <= b) || (b + c <= a)){cout << "输入的边长小于零或输入的边长不能构成三角形!" << endl;cout << "请重新输入三角形的三边长: ";cin >> a >> b >> c;}tmp = (a + b + c) / 2.0;TArea = sqrt(tmp * (tmp - a) * (tmp - b) * (tmp - c));return TArea;}class Rectangle : public Shape{private:double length, width;public:double RArea;double GetArea();};double Rectangle::GetArea(){cout << "请输入矩形的长和宽: ";cin >> length >> width;while(length < 0 || width < 0){cout << "矩形的长和宽不能小于零!" << endl;cout << "请重新输入矩形的长和宽: ";cin >> length >> width;}RArea = length * width;return RArea;}class Circle : public Shape{private:double Radius;public:double GetArea();};double Circle::GetArea(){cout << "请输入圆的半径: ";cin >> Radius;while(Radius < 0){cout << "圆的半径不能小于零!" << endl;cout << "请重新输入圆的半径: ";cin >> Radius;}CArea = 2 * PI * Radius;return CArea;}class Square : public Shape{private:double side;public:double SArea;double GetArea();};double Square::GetArea(){cout << "请输入正方形的边长: ";cin >> side;while(side < 0){cout << "正方形的边长不能小于零!" << endl;cout << "请重输入正方形的边长: ";cin >> side;}SArea = side * side;return SArea;}class triangle : public Shape{private:double UpBase, DownBase , Higth;public:double TArea;double GetArea();};double triangle::GetArea(){cout << "请输入梯形的上底,下底和高: ";cin >> UpBase >> DownBase >> Higth;while(UpBase < 0 || DownBase < 0 || Higth < 0){cout << "梯形的上底,下底和高不能小于零!" << endl;cout << "请重新输入梯形的上底,下底和高: ";cin >> UpBase >> DownBase >> Higth;}TArea = (UpBase + DownBase)* Higth / 2.0;return TArea;}void PrintArea(){Triangle myTri;Square mysqu;Circle mycir;Rectangle myrec;triangle mytri;cout << fixed << setprecision(2) << "三角形的面积: " << myTri.GetArea() << endl;cout << fixed << setprecision(2) << "正方形的面积: " << mysqu.GetArea() << endl;cout << fixed << setprecision(2) << "圆形的面积: " << mycir.GetArea() << endl;cout << fixed << setprecision(2) << "矩形的面积: " << myrec.GetArea() << endl;cout << fixed << setprecision(2) << "梯形的面积: " << mytri.GetArea() << endl;}int main(void){PrintArea();return 0;2.定义一个教师类,由教师类派生出讲师、副教授、教授类。
淮海工学院计算机科学系实验报告书课程名:《 C++程序设计(二)》题目:多态性和虚函数班级:学号:姓名:1、实验内容或题目(1)声明二维坐标类作为基类派生圆的类,把派生类圆作为基类,派生圆柱体类。
其中,基类二维坐标类有成员数据:x、y坐标值;有成员函数:构造函数实现对基类成员数据的初始化、输出的成员函数,要求输出坐标位置。
派生类圆类有新增成员数据:半径(R);有成员函数:构造函数实现对成员数据的初始化、计算圆面积的成员函数、输出半径的成员函数。
派生圆柱体类新增数据有高(H);新增成员函数有:构造函数、计算圆柱体体积的函数和输出所有成员的函数。
请完成程序代码的编写、调试。
(2)教材393页7-8题。
(3)教材416页1、4、5题。
2、实验目的与要求(1)理解继承与派生的概念(2)掌握通过继承派生出一个新的类的方法(3)了解多态性的概念(4)了解虚函数的作用与使用方法3、实验步骤与源程序⑴实验步骤先定义一个基类point,及其成员函数,然后以public的继承方式定义子类circle,再定义一个派生类cylinder,最后在main主函数中定义类对象,调用函数实现其功能。
先定义一个基类A及其重载的构造函数,然后以Public派生出子类B,再定义其构造函数,最后在main主函数中定义类对象,调用成员函数实现其功能。
⑵源代码1.#include <iostream.h>class Point{public:Point(float=0,float=0);void setPoint(float,float);float getX() const {return x;}float getY() const {return y;}friend ostream & operator<<(ostream &,const Point &); protected:float x,y;};Point::Point(float a,float b){x=a;y=b;}void Point::setPoint(float a,float b){x=a;y=b;}ostream & operator<<(ostream &output,const Point &p){cout<<"["<<p.x<<","<<p.y<<"]"<<endl;return output;}class Circle:public Point{public:Circle(float x=0,float y=0,float r=0);void setRadius(float);float getRadius() const;float area () const;friend ostream &operator<<(ostream &,const Circle &); protected:float radius;};Circle::Circle(float a,float b,float r):Point(a,b),radius(r){}void Circle::setRadius(float r){radius=r;}float Circle::getRadius() const {return radius;}float Circle::area() const{return 3.14159*radius*radius;}ostream &operator<<(ostream &output,const Circle &c){cout<<"Center=["<<c.x<<","<<c.y<<"], r="<<c.radius<<", area="<<c.area()<<endl;return output;}class Cylinder:public Circle{public:Cylinder (float x=0,float y=0,float r=0,float h=0);void setHeight(float);float getHeight() const;float area() const;float volume() const;friend ostream& operator<<(ostream&,const Cylinder&);protected:float height;};Cylinder::Cylinder(float a,float b,float r,float h):Circle(a,b,r),height(h){}void Cylinder::setHeight(float h){height=h;}float Cylinder::getHeight() const {return height;}float Cylinder::area() const{return 2*Circle::area()+2*3.14159*radius*height;}float Cylinder::volume() const{return Circle::area()*height;}ostream &operator<<(ostream &output,const Cylinder& cy){cout<<"Center=["<<cy.x<<","<<cy.y<<"], r="<<cy.radius<<", h="<<cy.height <<"\narea="<<cy.area()<<", volume="<<cy.volume()<<endl;return output;}int main(){Cylinder cy1(3.5,6.4,5.2,10);cout<<"\noriginal cylinder:\nx="<<cy1.getX()<<", y="<<cy1.getY()<<", r=" <<cy1.getRadius()<<", h="<<cy1.getHeight()<<"\narea="<<cy1.area()<<", volume="<<cy1.volume()<<endl;cy1.setHeight(15);cy1.setRadius(7.5);cy1.setPoint(5,5);cout<<"\nnew cylinder:\n"<<cy1;Point &pRef=cy1;cout<<"\npRef as a point:"<<pRef;Circle &cRef=cy1;cout<<"\ncRef as a Circle:"<<cRef;return 0;}2.(1)#include <iostream>using namespace std;class A{public:A(){a=0;b=0;}A(int i){a=i;b=0;}A(int i,int j){a=i;b=j;}void display(){cout<<"a="<<a<<" b="<<b;} private:int a;int b;};class B : public A{public:B(){c=0;}B(int i):A(i){c=0;}B(int i,int j):A(i,j){c=0;}B(int i,int j,int k):A(i,j){c=k;}void display1(){display();cout<<" c="<<c<<endl;}private:int c;};int main(){B b1;B b2(1);B b3(1,3);B b4(1,3,5);b1.display1();b2.display1();b3.display1();b4.display1();return 0;}(2)#include <iostream>using namespace std;class A{public:A(){cout<<"constructing A "<<endl;} ~A(){cout<<"destructing A "<<endl;} };class B : public A{public:B(){cout<<"constructing B "<<endl;} ~B(){cout<<"destructing B "<<endl;} };class C : public B{public:C(){cout<<"constructing C "<<endl;}~C(){cout<<"destructing C "<<endl;}};int main(){C c1;return 0;}3.(1)//Point.hclass Point{public:Point(float=0,float=0);void setPoint(float,float);float getX() const {return x;}float getY() const {return y;}friend ostream & operator<<(ostream &,const Point &); protected:float x,y;}//Point.cppPoint::Point(float a,float b){x=a;y=b;}void Point::setPoint(float a,float b){x=a;y=b;}ostream & operator<<(ostream &output,const Point &p){output<<"["<<p.x<<","<<p.y<<"]"<<endl;return output;}//Circle.h#include "point.h"class Circle:public Point{public:Circle(float x=0,float y=0,float r=0);void setRadius(float);float getRadius() const;float area () const;friend ostream &operator<<(ostream &,const Circle &);protected:float radius;};//Circle.cppCircle::Circle(float a,float b,float r):Point(a,b),radius(r){}void Circle::setRadius(float r){radius=r;}float Circle::getRadius() const {return radius;}float Circle::area() const{return 3.14159*radius*radius;}ostream &operator<<(ostream &output,const Circle &c){output<<"Center=["<<c.x<<","<<c.y<<"], r="<<c.radius<<", area="<<c.area()<<endl;return output;}//Cylinder.h#include "circle.h"class Cylinder:public Circle{public:Cylinder (float x=0,float y=0,float r=0,float h=0);void setHeight(float);float getHeight() const;float area() const;float volume() const;friend ostream& operator<<(ostream&,const Cylinder&);protected:float height;};//Cylinder.cppCylinder::Cylinder(float a,float b,float r,float h):Circle(a,b,r),height(h){}void Cylinder::setHeight(float h){height=h;}float Cylinder::getHeight() const {return height;}float Cylinder::area() const{ return 2*Circle::area()+2*3.14159*radius*height;}float Cylinder::volume() const{return Circle::area()*height;}ostream &operator<<(ostream &output,const Cylinder& cy){output<<"Center=["<<cy.x<<","<<cy.y<<"], r="<<cy.radius<<", h="<<cy.height<<"\narea="<<cy.area()<<", volume="<<cy.volume()<<endl;return output;}//main.cpp#include <iostream.h>#include "cylinder.h"#include "point.cpp"#include "circle.cpp"#include "cylinder.cpp"int main(){Cylinder cy1(3.5,6.4,5.2,10);cout<<"\noriginal cylinder:\nx="<<cy1.getX()<<", y="<<cy1.getY()<<", r=" <<cy1.getRadius()<<", h="<<cy1.getHeight()<<"\narea="<<cy1.area()<<", volume="<<cy1.volume()<<endl;cy1.setHeight(15);cy1.setRadius(7.5);cy1.setPoint(5,5);cout<<"\nnew cylinder:\n"<<cy1;Point &pRef=cy1;cout<<"\npRef as a point:"<<pRef;Circle &cRef=cy1;cout<<"\ncRef as a Circle:"<<cRef;return 0;}(2)#include <iostream>using namespace std;class Shape{public:virtual double area() const =0;class Circle:public Shape{public:Circle(double r):radius(r){} virtual double area() const {return 3.14159*radius*radius;}; protected:double radius;};class Rectangle:public Shape{public:Rectangle(double w,double h):width(w),height(h){} virtual double area() const {return width*height;} protected:double width,height; };class Triangle:public Shape{public:Triangle(double w,double h):width(w),height(h){} virtual double area() const {return 0.5*width*height;} protected:double width,height; };void printArea(const Shape &s)cout<<s.area()<<endl;} int main(){Circle circle(12.6);cout<<"area of circle =";printArea(circle);Rectangle rectangle(4.5,8.4);cout<<"area of rectangle =";printArea(rectangle);Triangle triangle(4.5,8.4);cout<<"area of triangle =";printArea(triangle);return 0;}(3)#include <iostream>using namespace std;class Shape{public:virtual double area() const =0;};class Circle:public Shape{public:Circle(double r):radius(r){}virtual double area() const {return 3.14159*radius*radius;}; protected:double radius;class Square:public Shape{public:Square(double s):side(s){}virtual double area() const {return side*side;}protected:double side;};class Rectangle:public Shape{public:Rectangle(double w,double h):width(w),height(h){}virtual double area() const {return width*height;}protected:double width,height; };class Trapezoid:public Shape{public:Trapezoid(double t,double b,double h):top(t),bottom(t),height(h){} virtual double area() const {return 0.5*(top+bottom)*height;} protected:double top,bottom,height;};class Triangle:public Shapepublic:Triangle(double w,double h):width(w),height(h){}virtual double area() const {return 0.5*width*height;} protected:double width,height;};int main(){Circle circle(12.6);Square square(3.5);Rectangle rectangle(4.5,8.4);Trapezoid trapezoid(2.0,4.5,3.2);Triangle triangle(4.5,8.4);Shape *pt[5]={&circle,&square,&rectangle,&trapezoid,&triangle};double areas=0.0;for(int i=0;i<5;i++){areas=areas+pt[i]->area();}cout<<"totol of all areas="<<areas<<endl;return 0;}4、测试数据与实验结果(可以抓图粘贴)5、结果分析与实验体会继承时,子类对基类的访问属性,基类的私有成员无论以何种方式继承在子类中都是不可访问的,唯有调用基类中的成员函数方可访问其私有变量。
[实验目的]1、了解多态性的概念;2、了解虚函数的用途及使用方法;3、了解纯虚函数和抽象类的概念和用法。
[实验要求]给出以下各实验内容的源程序代码,并把编译、运行过程中出现的问题以及解决方法填入实验报告中,按时上交。
[实验学时]2学时。
[实验内容]1、写一个程序,定义抽象基类Shape,由它派生出3个派生类:Circle(圆形)、Square(正方形)、Rectangle(矩形)。
利用指针、虚函数printArea()分别输出以上三者的面积,3个图形的数据在定义对象时给定。
[源程序]#include<iostream>using namespace std;class Shape{public:virtual float area()const=0;virtual void display()const=0;};class Circle:public Shape{public:Circle(double a):r(a){}virtual float area()const{return 3.14*r*r;}virtual void display()const{cout<<"圆面积"<<area()<<endl;}private:double r;};class Rectangle:public Shape{public:Rectangle(double a,double b):l(a),w(b){}virtual float area()const{return l*w;}virtual void display()const{cout<<"矩形面积"<<area()<<endl;}private:double l;double w;};class Square:public Shape{public:Square(double a):a1(a){}virtual float area()const{return a1*a1;}virtual void display()const{cout<<"正方形面积"<<area()<<endl;}private:double a1;};int main(){Circle c1(5);Rectangle r1(5,8);Square s1(2.5);Shape *p[3]={&c1,&r1,&s1};int i;double m=0.0;for (i=0;i<3;i++){p[i]->display();m=m+p[i]->area();}cout<<"总面积:"<<m<<endl;}2、定义Point(点)类,由Point类派生出Circle(圆)类,再由Circle类派生出Cylinder(圆柱体)类。
实验九:虚函数与多态性一.实验目的1.掌握动态联编的概念;2.掌握虚函数和纯虚函数的使用方法;3.掌握抽象类的使用。
二.实验内容设计一个计算图形面积的类库。
它的顶层是一个抽象类,并且提供相应的接口函数。
抽象基类Shape,派生出Point类、矩形Rectangle、正方形Square,Point类派生出圆形Circle。
要求:1、每个类有构造函数、析构函数,并有相应的输出语句,如:“正在构造圆形”2、能显示每个类的信息,如:输出“我是圆形”3、能计算面积、周长4、定义一个基类Shape类型的指针,实现动态多态5、动态创建一个圆形对象,赋值给基类Shape类型的指针变量,程序最后delete该指针,保证析构函数的正确调用(提示:虚析构函数)6、在主函数测试。
三.实验操作步骤1.输入源程序,编译、连接直到没有错误2.根据实验步骤,撰写实验报告四、实验要求1.复习教材中和实验相关的内容,提前编好程序。
2.整理上机结果,完成实验报告。
3.注意总结上机体会。
C++程序设计及实训198 #include <iostream>using namespace std;#include<string>class Shape{public:virtual float area()=0;virtual float longth()=0;virtual void show()=0;virtual ~Shape(){}};class Point:public Shape{protected:int x;int y;public:Point(int a=0,int b=0){x=a;y=b;cout<<"is constructing Point"<<endl;}void show(){cout<<"I am point"<<endl;}~Point(){cout<<"is destructing Point"<<endl;}float area(){return 0;}float longth(){实训2:简单C++程序设计return 0;}};class Rectangle:public Point{protected:int l;int w;public:Rectangle(int a=1,int b=1){l=a;w=b;cout<<"is constructing Rectangle"<<endl;}void show(){cout<<"I am Rectangle"<<endl;}float area(){return l*w;}float longth(){return 2*(l+w);}~Rectangle(){cout<<"is destructing Rectangle"<<endl;}};class Square:public Shape{protected:int r;public:Square(int a=1)199C++程序设计及实训200{r=a;cout<<"is constructing Square"<<endl;}void show(){cout<<"I am Square"<<endl;}float area(){return r*r;}float longth(){return 4*r;}~Square(){cout<<"is destructing Square"<<endl;}};class Circle:public Point{protected:int r;public:Circle(int a=1){r=a;cout<<"is constructing Circle"<<endl;}void show(){cout<<"I am Circle"<<endl;}float area(){return r*r*3.14;实训2:简单C++程序设计}float longth(){return 2*3.14*r;}~Circle(){cout<<"is destructing Circle"<<endl;}};int main(){Point a(1,1);Square b(2);Rectangle c(2,1);Shape *p=new Circle ;p->show();delete p;return 0;}{201。
实验六多态性和虚函数
一、实验目的
1、了解多态性的概念。
2、了解虚函数的作用及其使用方法。
3、了解静态关联和动态关联的概念和用法。
4、了解纯虚函数和抽象类的概念和用法。
二、实验要求
1、分析程序运行结果,掌握虚函数的使用。
程序一:
#include <iostream.h>
class ONE
{ public:
virtual void f(){cout<<"l"<<endl;}
};
class TWO:public ONE
{ public:
TWO(){cout<<"2"<<endl;}
};
class THREE:public TWO
{ public:
virtual void f(){TWO::f(); cout<<"3";}
};
void main()
{ ONE aa, *p;
TWO bb;
THREE cc;
p = &cc;
p->f();
}
程序二:
#include<iostream.h>
class Base
{ public:
virtual void fn() { cout <<"In Base Class\n";}
};
class SubClass :public Base
{ public:
virtual void fn(){ cout <<"In Sub Class\n"; }
};
void main()
{ Base bc,*p;
SubClass sc;
p=&bc; p->fn();
p=≻ p->fn();
}
2、实现一个类A,在A中有两个私有的整型变量a和b,定义构造函数对a和b进行初始化,并实现成员函数geta()取得a的值和getb()取b的值。
实现类B从A继承,覆盖geta(),使其返回a的2倍。
主函数中声明类B对象,调用类B中的geta()并将结果输出。
3、声明抽象基类Shape,由它派生出3个派生类:Cirle(圆形)、Rectangle(矩形)、Triangle (三角形),用一个函数printArea分别输出以上三者的面积,3个图形的数据在定义对象是给定。