实验六 多态性和虚函数

合集下载

第六章 多态性和虚函数

第六章 多态性和虚函数

例12.2 分析以下程序的执行结果 class unstudent { protected: int no; char name[10]; int fee1,fee2,fee3,fee4,fee; public: void calfee() { cout<<" 学号:"; cin>>no; cout<<" 姓名:"; cin>>name; fee1=4800; fee2=1100; fee3=400; fee4=200; fee=fee1+fee2+fee3+fee4; } void disp() { cout<<" 学 费:"<<fee1<<endl; cout<<" 住宿费:"<<fee2<<endl; cout<<" 书报费:"<<fee3<<endl; cout<<" 其 他:"<<fee4<<endl; cout<<" 总费用:"<<fee<<endl; } };
6.1 多态性的概念 6.2 一个典型的例子 6.3 虚函数 6.3.1 虚函数的作用 6.3.2 静态关联与动态关联
6.3.3 在什么情况下应当声明虚函数
6.3.4 虚析构函数 6.4 纯虚函数与抽象类
多态性(polymorphism):是面向对
象程序的一个重要特征
多态性:向不同的对象发送同一
消息,不同的对象在接收时会产生不 同的行为(即方法)

C++多态性实验报告含代码和结果截图

C++多态性实验报告含代码和结果截图

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 多态性与虚函数
实验6 多态性与虚函数
6.1 实验目的
1 .理解多态性的概念;
2 .掌握虚函数的作用及使用方法;
3 .了解静态关联和动态关联的概念和用法;
4 .了解纯虚函数和抽象类的概念和用法。

6.2 实验内容
程序设计部分
1 、定义平面图形的抽象基类figure,然后派生出四种几何图形是:三角形
/Triangle、矩形/Rectangle、正方形/Square和圆/Circle,利用基类指针和虚函数的多
态性来计算四种几何图形的面积和周长,这几何图形的参数通过构造函数来设置。

2 、定义立体图形的抽象基类shape,然后派生出:球、圆柱和圆锥,利用基类的引
用和虚函数的多态性来计算它们的表面积和体积。

本课程复习要点: 1、有关概念和知识点
变量的作用域和生存期,引用,常量,内联函数,函数重载,动态内存分配,输入/
输出流;类与对象,构造函数,拷贝构造函数,析构函数,友元;类成员的访问控制属性,this指针,静态成员,成员对象;派生/继承,多继承,构造函数调用顺序,虚基类;多态性与虚函数,抽象基类,运算符重载。

2、几个较完善的C++教学参考电子文档
3、练习:《C++程序设计基础与实践教程》习题解答、每个实验中的题目
感谢您的阅读,祝您生活愉快。

多态性和虚函数设计

多态性和虚函数设计
}
for(vector<Shape*>::iterator it=va.begin(); it!=va.end(); ++it)
(*it)->Display();
system("pause");
}
【实验结果】
【教师评语和成绩】
成绩:指导教师:日期:
输入文件shape.txt如下:
C 123 5 10
C 6 61 20
R 6 8 8 10
C 2 3 1
X
若第一个字符为'C',则后面为圆的数据
若第一个字符为'R',则后面为长方形的数据
若第一个字符为'X',表示输入结束
int main(){
vector<Shape*> va;
ifstream in("shape.txt");
Shape *ps;
char s;
double a,b,c,d,e,f;
for(;in>>s && s!='X' ;){
if(s=='C'){in>>a>>b>>c;ps=new Circle(a,b,c); va.push_back(ps);}
else if(s=='R'){
in>>a>>b>>c>>d;
姓名:
专业:
班级:
学号:
科目:
实验日期:
实验题目:多态性和虚函数设计
【实验目的】
1.在掌握继承与派生关系的基础上,进一步理解虚函数与多态性的关系,实现运行时的多态性。

实验6 多态性与虚函数

实验6     多态性与虚函数

实验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;}三.编程思想圆和立方体不属于同一类,这两类的参数不同计算方法不同,但是所求的都是面积输出的也都是面积这一个相同的成员函数。

第06章 多态性与虚函数

第06章 多态性与虚函数

void main() {point po(1,2),*p; rect re(3,4,10,12); p=&po; cout<<p->area()<<endl; p=&re; cout<<p->area()<<endl; }
程序运行结果如下: 0 120 所执行的成员函数是根据调 用该成员函数的指针所指向 的对象所在的类所决定的。
虚函数的几点说明
1. 当基类的成员函数被声明为虚拟的时候,其所有的派生类中,具有 相同名称、相同参数的成员函数都将自动成为虚拟的函数。
class A {public: virtual void disp(); };
class C:public B {public:
void disp(){cout<<"C";}
}; void main()
class B:public A
{publi} };
{C c;
A *p=&c; p->disp();
};
2、虚函数多态性只能通过指针或引用标识对象来操作虚函数。如果采用 一般类型的标识对象来操作虚函数,则将失去多态性,虚函数的声明也就 失去了意义。 #include "iostream.h" class point //定义一个点类 { private: int x,y;
name:wang int main() score:98.5 { Student stud1(1001,″Li″,87.5); // 定义Student类对象stud1 Graduate grad1(2001,″Wang″,98.5,563.5); // 定义Graduate类对象grad1 Student *pt=&stud1; // 定义指向基类对象的指针变量pt pt->display( ); pt=&grad1; pt->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. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验六多态性和虚函数
一、实验目的
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=&sc; 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个图形的数据在定义对象是给定。

相关文档
最新文档