C++ 实验多态性实验报告
C++多态性实验报告含代码和结果截图
![C++多态性实验报告含代码和结果截图](https://img.taocdn.com/s3/m/b19a0b0a876fb84ae45c3b3567ec102de3bddf5c.png)
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;<>。
实验报告多态性
![实验报告多态性](https://img.taocdn.com/s3/m/7108e2a6951ea76e58fafab069dc5022abea461e.png)
一、实验目的1. 理解多态性的概念及其在面向对象编程中的重要性。
2. 掌握多态性的实现方式,包括方法重载和方法覆盖。
3. 学习如何利用多态性提高代码的可读性和可维护性。
4. 通过实例分析,加深对多态性在实际编程中的应用理解。
二、实验背景多态性是面向对象编程中的一个核心概念,它允许同一个接口(或方法)根据不同的数据类型执行不同的操作。
在Java、C++等面向对象编程语言中,多态性主要通过方法重载和方法覆盖来实现。
三、实验内容1. 方法重载方法重载是指在同一个类中,允许存在多个同名方法,但参数列表不同。
编译器通过参数列表的匹配来确定调用哪个方法。
(1)实验步骤1)创建一个名为“Animal”的类,包含一个方法名为“makeSound”。
2)在“Animal”类中,添加三个重载的“makeSound”方法,分别接受不同类型的参数(如int、String、double)。
3)创建一个名为“Dog”的类,继承自“Animal”类,并重写“makeSound”方法,使其输出“Woof! Woof!”。
4)创建一个名为“Cat”的类,继承自“Animal”类,并重写“makeSound”方法,使其输出“Meow! Meow!”。
(2)实验结果当创建“Dog”和“Cat”对象时,调用“makeSound”方法会根据对象类型输出相应的声音。
2. 方法覆盖方法覆盖是指在子类中重写父类的方法,使子类的方法具有与父类方法相同的签名,但具有不同的实现。
(1)实验步骤1)创建一个名为“Vehicle”的类,包含一个方法名为“move”,该方法无参数。
2)创建一个名为“Car”的类,继承自“Vehicle”类,并重写“move”方法,使其输出“Car is moving”。
3)创建一个名为“Bike”的类,继承自“Vehicle”类,并重写“move”方法,使其输出“Bike is moving”。
(2)实验结果当创建“Car”和“Bike”对象时,调用“move”方法会根据对象类型输出相应的移动信息。
C++程序设计实验报告(多态性)
![C++程序设计实验报告(多态性)](https://img.taocdn.com/s3/m/96765e234b35eefdc8d333ab.png)
西安科技大学《C/C++语言程序设计》实验报告题目)___院、系(部) ___________专业及班级 ________姓名 _________ 学号日期 ____一系统功能分析用同一个名字来访问不同函数的性质即为多态性,使用多态性,一些功能相似的函数可用同一个名字来定义,这样会使得概念更清晰,还可达到动态链表的目的,实现运行的多态性以下程序使用了函数的重载,其使用对象名加以区分,还是用:类名::加以区分。
二总体设计学生系统分析图三详细设计1 首先,定义一个类名为student的类class Student{char name[20];int num;int age;public:void Build();void Delete();void correct();void seek();Student(){strcpy(name,"");num=0;age=0;}Student(char nam[20],int nu,int ag){strcpy(name,nam);num=nu;age=ag;}void show(){cout<<"name:"<<name[20]<<endl;cout<<"num:"<<num<<endl;cout<<"age:"<<age<<endl;}~Student(){}};2 然后,在外面有各种功能函数的实现函数 Student *p[100];int i=0;int j=0;char name[20];int num;int age;void Student::Build(){Student *p[100];cout<<"name:"<<endl;cin>>p[i]->name[20];cout<<"num:"<<endl;cin>>p[i]->num;cout<<"age:"<<endl;cin>>p[i]->age;j++;p[i]=new Student();i++;}void Student::Delete(){cout<<"请输入您要删除的学生到底姓名:"<<endl; cin>>name;for(int s=0;s<i;s++){if(strcmp(name,p[s]->name)==0){i--;p[s]=p[s+1];s++;}cin.clear();}}void Student::correct(){cout<<"请输入您要改正学生信息的学生姓名:"<<endl;cin>>name[20];// char name[20];int num;int age;for(int s=0;s<i;s++){if(strcmp(name,p[s]->name)==0){cout<<"name:"<<p[s]->name<<endl;cout<<"num:"<<p[s]->num<<endl;cout<<"age:"<<p[s]->age<<endl;}}}void Student::seek(){//char name[20],int num,int age;cout<<"请输入学生的姓名:"<<endl;cin>>name[20];for(int s=0;s<i;s++){if(strcmp(name,p[s]->name)==0){cout<<"该学生的信息为:"<<endl;cout<<"name:"<<name[20]<<endl;cout<<"num:"<<num<<endl;cout<<"age:"<<age<<endl;break;}}}3 在函数yunxing中对上述函数进行调用void yunxing(int n){Student m;switch(n){case 1:m.Build();break;case 2:m.Delete();break;case 3:m.correct();break;case 4:m.seek();break;}4 在main函数中写出欢迎界面和初始化语句Student s1("lili",1101,19);Student s2("wangfang",1102,20);Student s3("wangmeng",1103,18);Student s4("linan",1104,21);Teacher t1("liangshaohui",1105,30,5000,"gaoshu");Teacher t2("liuwei",1106,29,6000,"dawu");Teacher t3("yuyawei",1107,28,7000,"lisan");Teacher t4("chenming",1108,27,8000,"yingyu");s1.show();s2.show();s3.show();s4.show();t1.show();t2.show();t3.show();t4.show();t1.Student::show();t2.Student::show();t3.Student::show();t4.Student::show();cout<<" 菜单界面 \n"<<endl;cout<<" 1:新建用户信息 \n"<<endl;cout<<" 2:删除用户信息 \n"<<endl;cout<<" 3:改正用户信息 \n"<<endl;cout<<" 4:查找用户信息 \n"<<endl;cout<<"请选择你要选择的项目! "<<endl;四测试与实现五总结之前我们用C语言编写的程序-学生管理系统是非常繁琐的,后来我们学习了C++语言,学习了类与对象,学习了继承与派生,最后学习了多态性,一步步的我们在原先的学生管理系统中添加了这些函数,可以明显的感觉到程序在一步步简化,一步步完善,这便突出了C++语言的简捷。
C++程序设计实验报告-多态性
![C++程序设计实验报告-多态性](https://img.taocdn.com/s3/m/4a492e310722192e4536f670.png)
(2)定义一个车(vehiele)基类,有 Run、Stop 等成员函数,由此派生出自 行车(bicycle)类、汽车(motorcar)类,从 bicycle 和 motorcar 派生出摩托车 (motorcycle)类,它们都有 Run、Stop 等成员函数。观察虚函数的作用。 源程序代码:
class bicycle:public vehicle { public:
void run() const{cout<<"bicycle 开始运行"<<endl; void stop() const{cout<<"bicycle 停止运行"<<endl; };
class motorcar:public vehicle { public:
#include<iostream> using namespace std; class Point { public:
Point& operator++(); Point operator++(int); Point& operator--(); Point operator--(int); Point(){_x=_y=0;} int x(){return _x;} int y(){return _y;} private: int _x,_y; };
Point& Point::operator++() {
_x++; _y++; return *this; } Point Point::operator++(int) { Point temp=*this; ++ *this; return temp; } Point& Point::operator--() { _x--; _y--; return *this; } Point Point::operator--(int) { Point temp=*this; -- *this; return temp; }
c 多态性的实验报告
![c 多态性的实验报告](https://img.taocdn.com/s3/m/f5f6782a7f21af45b307e87101f69e314332faa2.png)
c 多态性的实验报告C++多态性的实验报告引言:多态性是面向对象编程中的一个重要概念,它允许我们使用统一的接口来处理不同类型的对象。
在C++中,多态性通过虚函数和继承来实现。
本实验旨在通过一个简单的实例来演示C++多态性的使用方法和效果。
实验目的:1. 理解多态性的概念和原理;2. 掌握在C++中实现多态性的方法;3. 通过实例了解多态性的实际应用。
实验步骤:1. 创建基类Animal和派生类Dog、Cat;2. 在基类中声明虚函数"makeSound()",并在派生类中实现该函数;3. 在主函数中创建Animal类型的指针数组,分别指向Dog和Cat对象;4. 通过循环调用虚函数"makeSound()",观察不同对象的行为。
实验结果:在本实验中,我们创建了一个基类Animal和两个派生类Dog、Cat。
Animal类中声明了虚函数"makeSound()",而Dog和Cat类分别实现了该函数。
在主函数中,我们创建了一个Animal类型的指针数组,分别指向Dog和Cat对象。
通过循环调用虚函数"makeSound()",我们可以观察到不同对象的行为。
实验分析:1. 多态性的实现:多态性通过虚函数和继承来实现。
在本实验中,通过将基类中的函数声明为虚函数,我们可以在派生类中重写该函数,从而实现多态性。
通过使用基类指针数组,我们可以在运行时动态地确定调用哪个对象的函数。
2. 多态性的优势:多态性使得程序更加灵活和可扩展。
通过使用统一的接口处理不同类型的对象,我们可以减少代码的重复性,提高代码的可读性和可维护性。
此外,多态性还支持运行时的动态绑定,使得程序可以根据实际情况来决定调用哪个函数,从而更好地适应不同的需求。
3. 多态性的应用:多态性在实际应用中有着广泛的应用。
例如,在图形界面程序中,我们可以通过多态性来处理不同类型的控件;在游戏开发中,我们可以通过多态性来处理不同类型的角色和敌人;在工程设计中,我们可以通过多态性来处理不同类型的零件和设备。
c多态实验报告
![c多态实验报告](https://img.taocdn.com/s3/m/46b9aceed1d233d4b14e852458fb770bf78a3bc2.png)
c多态实验报告一、实验目的本次实验旨在深入理解和掌握 C 语言中的多态特性,通过实际编程和测试,探究多态在不同场景下的应用和效果,提高对 C 语言编程的综合运用能力。
二、实验环境操作系统:Windows 10编译器:GCC 1020三、实验原理多态是面向对象编程中的重要概念,在 C 语言中,主要通过函数指针来实现。
函数指针可以指向不同的函数,根据不同的条件执行不同的函数,从而实现多态的效果。
四、实验内容与步骤1、定义函数指针类型首先,定义一个函数指针类型,例如:```ctypedef int (Operation)(int, int);这里定义了一个名为`Operation` 的函数指针类型,它指向的函数接受两个`int` 类型的参数,并返回一个`int` 类型的值。
2、实现不同的具体函数接下来,实现具体的操作函数,如加法、减法、乘法等:```cint add(int a, int b) {return a + b;}int subtract(int a, int b) {return a b;}int multiply(int a, int b) {return a b;}```3、使用函数指针进行多态操作在主函数中,通过函数指针来调用不同的具体函数,实现多态效果:int main(){Operation op;op = add;int result1 = op(5, 3);op = subtract;int result2 = op(5, 3);op = multiply;int result3 = op(5, 3);printf("加法结果:%d\n", result1);printf("减法结果:%d\n", result2);printf("乘法结果:%d\n", result3);return 0;}```五、实验结果运行上述代码,得到的结果如下:加法结果:8减法结果:2乘法结果:15可以看到,通过函数指针的切换,实现了不同的运算操作,达到了多态的效果。
c 多态性实验报告
![c 多态性实验报告](https://img.taocdn.com/s3/m/244bbec86429647d27284b73f242336c1eb930d3.png)
c 多态性实验报告C++多态性实验报告引言:多态性是面向对象编程中的一个重要概念,它允许我们以一种统一的方式处理不同类型的对象。
在C++中,多态性通过虚函数和指针或引用来实现。
本实验旨在探索C++中多态性的实际应用,并通过实验结果来验证其效果。
实验步骤:1. 创建基类和派生类:首先,我们创建一个基类Animal,其中包含一个虚函数makeSound()用于发出动物的声音。
然后,我们创建两个派生类Dog和Cat,它们分别继承自Animal 类,并实现自己的makeSound()函数。
2. 创建动态数组:接下来,我们创建一个动态数组,其中包含不同类型的动物对象。
这样我们就可以在一个数组中存储不同类型的对象,并以统一的方式处理它们。
3. 调用虚函数:通过使用基类指针或引用,我们可以调用派生类中的虚函数。
这样,无论基类指针指向的是派生类的对象还是基类的对象,都可以正确地调用派生类的函数。
我们可以通过遍历动态数组来调用每个动物对象的makeSound()函数,并观察到不同类型的动物发出不同的声音。
实验结果:我们创建了一个动态数组,其中包含了两个Dog对象和两个Cat对象。
通过遍历数组并调用makeSound()函数,我们观察到每个动物对象都发出了与其类型相对应的声音。
这证明了多态性的实际应用,即通过统一的接口处理不同类型的对象。
讨论与总结:多态性是面向对象编程中的重要概念,它提供了一种灵活的方式来处理不同类型的对象。
通过使用虚函数和基类指针或引用,我们可以以统一的方式处理派生类对象,并实现动态绑定。
这种灵活性使得我们的代码更加可扩展和可维护。
然而,多态性也带来了一些性能开销。
由于需要在运行时确定函数的调用地址,多态性可能会导致一定的性能损失。
因此,在实际编程中,我们需要根据具体情况来权衡使用多态性的利与弊。
总之,本实验通过实际应用验证了C++中多态性的效果,并讨论了其优缺点。
多态性是面向对象编程中的重要概念,对于提高代码的可扩展性和可维护性具有重要意义。
c运算符重载和多态性实验报告
![c运算符重载和多态性实验报告](https://img.taocdn.com/s3/m/148bb2cbed630b1c58eeb542.png)
实验5 运算符重载和多态性一、实验目的1.掌握用成员函数重载运算符的方法2.掌握用友元函数重载运算符的方法3.理解并掌握利用虚函数实现动态多态性和编写通用程序的方法4.掌握纯虚函数和抽象类的使用二、实验内容1.复数类加减法乘除运算 (用成员函数定义运算符重载)。
复数类的定义:class complex //复数类声明{ public: //外部接口complex(double r=0.0,double i=0.0) //构造函数{real=r,imag=i;}complex operator +(complex c2); //运算符"+"重载成员函数complex operator - (complex c2); //运算符"-"重载成员函数complex operator *(complex ); //运算符"*"重载成员函数complex operator /(complex); //运算符"/"重载成员函数complex operator =(complex c2); //运算符"="重载成员函数void display(); //输出复数private: //私有数据成员double real; //复数实部double imag; //复数虚部};实验代码:#include <iostream>using namespace std;class Complex{public:Complex(){real=0;imag=0;}Complex(double r,double i){real=r;imag=i;}Complex operator+(Complex &c2); Complex operator-(Complex &c2); Complex operator*(Complex &c2); Complex operator/(Complex &c2); void display();private:double real; double imag;};Complex Complex::operator+(Complex &c2) {Complex c;c.real=real+c2.real;c.imag=imag+c2.imag; return c;}Complex Complex::operator-(Complex &c2) {Complex c;c.real=real-c2.real;c.imag=imag-c2.imag;return c;}Complex Complex::operator*(Complex &c2) {Complex c;c.real=real*c2.real-imag*c2.imag;c.imag=imag*c2.real+real*c2.imag; return c;}Complex Complex::operator/(Complex &c2){Complex c;c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag );c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);return c;}void Complex::display(){cout<<"("<<real<<","<<imag<<"i)"<<endl;}int main(){Complex c1(4,6),c2(3,7),c3;cout<<"c1=";c1.display();cout<<"c2=";c2.display();int i,j=1;while(j){cout<<"\n";cout<<"\t\t"<<"1.复数之和\n"; cout<<"\t\t"<<"2.复数之差\n"; cout<<"\t\t"<<"3.复数之积\n"; cout<<"\t\t"<<"4.复数之商\n"; cout<<"\t\t"<<"0.退出\n"; cout<<"请选择(0--4)"; cin>>i;switch(i){case 1: c3=c1+c2;cout<<"c1+c2=";c3.display(); break;case 2: c3=c1-c2;cout<<"c1-c2=";c3.display();break;case 3: c3=c1*c2;cout<<"c1*c2=";c3.display();break;case 4: c3=c1/c2;cout<<"c1/c2=";c3.display();break;case 0: j=0;break;}}}测试结果:2.复数类比较运算 (用友元函数定义运算重载)。
c++类的多态性的实现实验3报告
![c++类的多态性的实现实验3报告](https://img.taocdn.com/s3/m/8c9701d026fff705cc170ab3.png)
实验报告一、实验名称:类的多态性的实现二、实验目的:1)掌握用成员函数重载运算符的方法2)掌握用友元函数重载运算符的方法三、实验内容:模拟STL库中string类的功能,编写MyString类,至少实现字符串间的赋值、比较(包括>、<、=、!=)和字符串间的”+”(连接)操作,同时能通过下面列举的形式对字符串对象进行初始化。
如:MyString str1(“I am ”),str2=“a student”;if(str1>str2) cout<<“larger\n”;if(str1<str2) cout<<“smaller\n”;if(str1==str2) cout<<“equal\n”;if(str1!=str2) cout<<“unequal\n”;MyString str3=str1+str2;思考在为字符串分配空间时采用动态还是静态的分配方式,各有什么优缺点。
四、实验结果:#include<string.h>#include<iostream.h>class MyString{public:MyString(char *s=""){ str=new char[strlen(s)+1];strcpy(str,s);return;}MyString(const MyString& other){ str=new char[strlen(other.str)+1];strcpy(str,other.str);return;}int operator >(MyString& right) //重载>运算符{ int n;n=strcmp(str,right.str);if(n>0)return 1;else return 0;}int operator <(MyString& right) //重载<运算符{int n=strcmp(str,right.str);if(n<0)return 1;else return 0;}int operator ==(MyString& right) //重载==运算符 {int n=strcmp(str,right.str);if(n==0)return 1;else return 0;}int operator !=(MyString& right) //重载!=运算符 {int n=strcmp(str,right.str);if(n!=0)return 1;else return 0;}MyString operator +(MyString& right) //重载+运算符 {MyString temp;temp.str=strcat(str,right.str);return temp;}~MyString() // 析构函数{ return; }char* getstr() //取类中字符{ return str; }private :char *str;};void main(){MyString str1("I am "),str2="a student";if(str1>str2) cout<<"larger\n";if(str1<str2) cout<<"smaller\n";if(str1==str2) cout<<"equal\n";if(str1!=str2) cout<<"unequal\n";MyString str3=str1+str2;cout<<str3.getstr()<<endl; //输出str3类中字符 return;}[运行结果]思考题:字符串静态分配优点:使用方便缺点:定义的数组过大,会浪费大量的内存空间,定义的数组不够大时,可能引起下标越界错误,甚至导致严重后果。
C 实验多态性实验报告
![C 实验多态性实验报告](https://img.taocdn.com/s3/m/126ab905c281e53a5802ff51.png)
class Point { public:
Point(int xx,int yy):x(xx),y(yy) {} void display()const; Point &operator++(); Point operator++(int); Point &operator--(); Point operator--(int); private:
using namespace std;
int Double(int x);
long Double(long x);
float Double(float x);
double Double(double x);
int main()
{ int myInt = 6500;
cout<<Double(myInt)<<endl;
学习使用虚函数实现动态多态性。而虚函数就是在基类中被关键字 virtual 说明,
实 并在派生类中重新定义的函数,且在派生类中重工业新定义时,函数原型,包括返回
类型、函数名、参数个数与参数类型的顺序,都必须与基类中的完全相同。此外,构 验
造函数不能是虚函数,但析构函数可以是虚函数。
总
函数的重载方法有一参数个数相同,但是类型不同;二参数个数不同;三 coust
实
验 Visual C++的编译环境下,独立完成实验要求的内容,独立完成编写、编译以及运行
原
的过程
理
实
验 安装了 Visual C++的 PC 机器
仪
器
多态性 c 实验报告
![多态性 c 实验报告](https://img.taocdn.com/s3/m/d27e7d29ae1ffc4ffe4733687e21af45b307fed9.png)
多态性 c 实验报告多态性 C 实验报告引言:多态性是面向对象编程中的一个重要概念,它允许不同的对象对同一个消息作出不同的响应。
在C语言中,虽然没有直接支持多态性,但我们可以通过一些技巧来模拟实现。
本实验旨在通过一个简单的案例来探索C语言中的多态性,并探讨其优缺点。
实验设计:我们设计了一个简单的图形库,其中包含了三种不同的图形:矩形、圆形和三角形。
每个图形都有一个绘制函数,用于在屏幕上绘制相应的图形。
我们通过使用函数指针和结构体来实现多态性。
实验过程:首先,我们定义了一个图形的基类结构体,用于存储图形的类型和绘制函数的指针。
然后,我们定义了三个派生类结构体,分别表示矩形、圆形和三角形。
每个派生类结构体都包含了一个继承自基类的成员,用于存储特定图形的属性(如矩形的宽度和高度)。
接下来,我们定义了一个绘制函数,该函数接受一个指向基类结构体的指针作为参数。
在函数内部,我们通过判断图形的类型,调用相应的绘制函数来实现多态性。
例如,如果传入的图形是矩形,则调用矩形的绘制函数,以此类推。
在主函数中,我们创建了一个包含不同类型图形的数组,并依次调用绘制函数来绘制这些图形。
由于我们使用了多态性的实现,即使是相同的函数名,不同类型的图形也能够调用各自的绘制函数,从而实现了多态性。
实验结果:经过编译和运行,我们成功地绘制出了矩形、圆形和三角形。
每个图形都按照其特定的形状和属性在屏幕上绘制出来。
这证明了我们通过函数指针和结构体模拟实现的多态性是有效的。
讨论:尽管C语言本身没有直接支持多态性的特性,但我们可以通过一些技巧来模拟实现。
使用函数指针和结构体是一种常见的方法,它允许不同类型的对象调用相同的函数名,从而实现了多态性。
然而,这种模拟实现也存在一些局限性。
首先,由于C语言的静态类型特性,我们需要在编译时确定对象的类型,无法在运行时动态确定。
这意味着我们需要手动管理对象的类型,并在调用函数时进行判断,增加了一定的复杂性。
实验六c++
![实验六c++](https://img.taocdn.com/s3/m/a595e7ca8bd63186bcebbc65.png)
福建农林大学金山学院实验报告系(教研室):信息与机电工程系专业:计算机科学与技术年级:2009实验课程:多态性(一)姓名:学号:092231048 实验室号612计算机号J612S048 实验时间:2015-5-27 指导教师签字:成绩:实验6 多态性(一)一、实验目的和要求(1)掌握虚函数的定义与使用方法,进一步理解多态性的概念和分类。
(2)了解纯虚函数和抽象类的使用方法。
二、实验内容和原理1、分析并调试下列程序,回答以下问题:(1)指出抽象类(2)指出虚函数,并说明它的作用(3)每个类的作用是什么?整个程序的作用是什么?2、使用虚函数编写程序求球体、圆柱体和圆锥的体积,由于球体、圆柱体和圆锥都可以看做由圆继承而来,所以可以定义圆类作为基类。
在圆类中定义数据成员半径和一个求体积的虚函数。
由圆类派生出球体类、圆柱体类和圆锥类,在派生类中对圆类中的虚函数重新定义。
编写一个外部函数求各类形状的总体积。
最后在main()函数中构造若干形状,并求它们的体积和。
三、实验环境1. 硬件:PC机;2. 软件:Windows操作系统、Visual C++ 6.0四、算法描述及实验步骤1、#include<iostream.h>const double PI=3.1415;class Shap{public:virtual double Area()=0;};class Triangle:public Shap{public:Triangle(double h,double w){H=h;W=w;}double Area(){return 0.5*H*W;}private:double H,W;};class Circle:public Shap{public:Circle(double r){R=r;}double Area(){return PI*R*R;}private:double R;};double Total(Shap *s[],int n){double sum=0;for(int i=0;i<n;i++){sum+=s[i]->Area();}return sum;}int main(){Shap *s[2];s[0]=new Triangle(5.0,4.0);s[1]=new Circle(8.0);double sum=Total(s,2);cout<<"sum="<<sum<<endl;return 0;}(1)抽象类是Shap类。
C实验报告-实验5多态性与虚函数
![C实验报告-实验5多态性与虚函数](https://img.taocdn.com/s3/m/d692bdf4da38376bae1fae2e.png)
实验5 多态性与虚函数一、实验目的和要求了解静态联编和动态联编的概念。
掌握动态联编的条件。
二、实验内容和原理事先编写好程序,上机调试和运行程序,分析结果。
(1)实验指导书P96 1~4任选一题。
(2)实验指导书P100 5~6任选一题。
三、实验环境联想计算机,Windows XP操作系统,Visual C++ 6.0四、算法描述及实验步骤(1)编写源程序。
(2)检查程序有无错误(包括语法错误和逻辑错误),有则改之。
(3)编译和连接,仔细分析编译信息,如有错误应找出原因并改正之。
(4)运行程序,分析结果。
(5)将调试好的程序保存在自己的用户目录中,文件名自定。
五、调试过程12六、实验结果15七、总结动态联编需要满足3个条件,首先类之间满足类型兼容规则;第二是要声明虚函数;第三是要由成员函数来调用或者是通过基类指针、引用来访问虚函数。
附录:1.public:virtual void f(float x){cout<<"Base::f(float)"<<x<<endl;} void g(float x){cout<<"Base::g(float)"<<x<<endl;}void h(float x ){cout<<"Base::h(float)"<<x<<endl;} };class Derived:public Base{public:virtual void f(float x){cout<<"Derived::h(float)"<<x<<endl;}};int main(){Derived d;Base * pb=&d;Derived *pd=&d;pb->f(3.14f);pb->f(3.14f);pb->g(3.14f);pb->h(3.14f);pb->h(3.14f);return 0;}2#include<iostream>using namespace std;#include<string>class Teacher{public:Teacher(string n,int h);virtual double salary()=0;virtual void print()=0;protected:string name;int lessons;};Teacher::Teacher(string n,int h){name=n;lessons=h;}class Professor:public Teacher{public:Professor(string n,int h):Teacher(n,h){}double salary(){return 5000 + 50 * lessons;}void print();void Professor::print(){cout<<name<<"\tProfessor\t\t"<<lessons<<"lessons"; cout<<"\tearned ¥"<<salary()<<endl;}class Associateprofessor:public Teacher{public:Associateprofessor(string n,int h):Teacher(n,h){}double salary(){return 3000+30*lessons;}void print();};void Associateprofessor::print(){cout<<na#include<iostream>using namespace std;#include<string>class Teacher{public:Teacher(string n,int h);virtual double salary()=0;virtual void print()=0;protected:string name;int lessons;};Teacher::Teacher(string n,int h){name=n;lessons=h;}class Professor:public Teacher{public:Professor(string n,int h):Teacher(n,h){}double salary(){return 5000 + 50 * lessons;}void print();};void Professor::print(){cout<<name<<"\tProfessor\t\t"<<lessons<<"lessons"; cout<<"\tearned ¥"<<salary()<<endl;}class Associateprofessor:public Teacher{public:Associateprofessor(string n,int h):Teacher(n,h){}double salary(){return 3000+30*lessons;}void print();};void Ass me<<"\tAssociateprofessor\t"<<lessons<<"lessons"; cout<<"\tearned ¥"<<salary()<<endl;}class Lecturer:public Teacher{public:Lecturer(string n,int h):Teacher(n,h){}double salary(){return 2000+20*lessons;}void print();};void Lecturer::print(){cout<<name<<"\tLecturer\t\t"<<lessons<<"lessons";cout<<"\tearned ¥"<<salary()<<endl;}int main(){Teacher * t[3];t[0]=new Professor("Tang XiHua",12);t[1]=new Associateprofessor("Li HanPin",16);t[2]=new Lecturer("Zhang Y ue",20);for(int i=0;i<3;i++){t[i]->print();delete t[i];}return 0;}。
C++多态性实验
![C++多态性实验](https://img.taocdn.com/s3/m/911de345fe4733687e21aa09.png)
《C++面向对象程序设计》实验报告实验序号:4 实验项目名称:多态性附:程序源代码1、2、#include<iostream> #include<string> using namespace std;class Time{public:Time(){hours=0;minutes=0;seconds=0;}Time(int h,int m,int s){ hours=h;minutes=m;seconds=s;}Time operator+(Time&t2);void disptime();private:int hours;int minutes;int seconds;};Time Time:: operator+(Time&t2){Time t;t.hours=hours+t2.hours;t.minutes=minutes+t2.minutes;t.seconds=seconds+t2.seconds;if(t.seconds>=60){t.seconds=t.seconds-60;t.minutes=t.minutes+1;}if(t.minutes>=60){t.minutes=t.minutes-60;t.hours=t.hours+1;}return t;}void Time::disptime(){ cout<<hours<<":"<<minutes<<":"<<seconds<<endl;}int main(){Time t1(10 ,20,30) ,t2(12,35,40),t3;t3=t1+t2;cout<<"t1=";t1.disptime();cout<<"t2=";t2.disptime();cout<<"t1+t2:"<<" ";t3.disptime();return 0;}3、#include<iostream>#include<string>using namespace std;class container{protected:double radius;public:container(double radius1);virtual double surface_area()=0;virtual double volume()=0;};container::container(double radius1){radius=radius1;}class Cube:public container{public:Cube(double radius1):container( radius1){}double surface_area(){ return 6*radius*radius;}double volume(){return radius*radius*radius;}};class sphere:public container{public:sphere (double radius1):container(radius1){}double surface_area(){return 4*radius*radius*3.14159;}double volume(){ return 4/3*radius*radius*radius*3.14159;}};class cylinder:public container{public:double height;cylinder (double radius1,double h):container(radius1){ height=h ; }double surface_area(){ return 4*height*radius;}double volume(){ return 3.14159*radius*radius*height;}};int main(){ Cube c1(6.0);sphere s1(5.0);cylinder y1(5.0,6.0);container *pt;pt=&c1;cout<<"cube:"<<endl<<"area is "<<pt-> surface_area()<<endl; cout<<" volume is "<<pt->volume()<<endl<<endl;pt=&s1;cout<<" sphere:"<<endl<<"area is "<<pt-> surface_area()<<endl; cout<<" volume is "<<pt->volume()<<endl<<endl;pt=&y1;cout<<" cylinde:"<<endl<<"area is "<<pt-> surface_area()<<endl; cout<<" volume is "<<pt->volume();return 0;}4、#include<iostream>using namespace std;const int MAX = 50;class set{public:set();void input(int d);int length();int getd(int i);void disp();set operator+(set s1);set operator-(set s1);set operator*(set s1);set operator=(set s1);protected:int len;int s[MAX];};set::set(){len = 0;}void set::input(int d){len = d;cout<< "输入集合元素" << d <<" 个:";for(int i =0; i < d; i++ )cin>> s[i] ;}int set::length(){int n=0;while(s[n]!= '\0'){n++;}return n;}int set::getd(int i){return 0;}void set::disp(){for (int i= 0; i < len; i++)cout<< s[i] << " ";}set set::operator+(set s1) //------并运算-------{for (int i = 0; i < len; i++){for(int j = 0; j < s1.len; j++) //在s1.s[]中选出不相同的{if(s[i] == s1.s[j]) //选出相同的元素删掉得到s1.s与s不同的元素{for (;j < s1.len; j++)s1.s[j]= s1.s[j+1];--s1.len;}}}for (int j = 0;j < s1.len; j++ ) // 将s1.s[]中不相同的加在s[]后面{s[len] = s1.s[j];len++;}s[len+s1.len] = '\0';return *this;}set set::operator-(set s1) //-----------差运算-----------{int t;for (int i= 0; i < s1.len; i++){for(int j=0;j<len;j++){if(s1.s[i] == s[j] ) //选出s与s1.s中相同的元素并且删除掉{t= j;for (;t < len; t++)s[t]= s[t+1];--len;}}}return *this;}set set::operator*(set s1) // -------交运算------- {int m[MAX];int l = 0;for (int i= 0; i < s1.len; i++){for(int j = 0; j < len; j++) // 选出相同的元素{if(s1.s[i] == s[j]){m[l] = s[j];l++;}}}for (i = 0;i < l; i++)s[i]= m[i];s[l] ='\0';len = l;return *this;}set set::operator=(set s1){for (int i= 0; i < s1.length(); i++)s[i] = s1.s[i];len =s1.len;return *this;}int main(){int n;set C1;set A1;cout<< "建立含有几个元素的集合:";cin>> n;A1.input(n);set B1;cout<< "建立含有几个元素的集合:";cin>> n;B1.input(n);cout<< "两集合的差集(A1 - B1)为:";C1 = A1 -B1;C1.disp();cout<< endl<<endl;int W;set C2;set A2;cout<< "建立含有几个元素的集合:";cin>> W;A2.input(W);set B2;cout<< "建立含有几个元素的集合:";cin>> W;B2.input(W);cout<<"两合集的交集(A2*B2)为:";C2 = A2 *B2;C2.disp();cout<<endl;int p ;set C3;set A3;cout<< "建立含有几个元素的集合:";cin>> p;A3.input(p);set B3;cout<< "建立含有几个元素的集合:";cin>> p;B3.input(p);cout<< "两集合的并集(A3 + B3)为:";C3 = A3 +B3;C3.disp();cout<< endl;return 0;}5、6、。
C#有关多态的实验报告
![C#有关多态的实验报告](https://img.taocdn.com/s3/m/9d714167ddccda38376baf5f.png)
课程名称面向对象的程序设计班级xx 实验日期2012年3月21日姓名xx 学号xx 实验成绩实验名称创建抽象类并实现多态实验目的及要求1、掌握简单的C#程序结构。
2、熟悉Visual Studio 2010集成开发环境。
3、能够在Visual Studio 2010集成开发环境下创建简单的控制台和windows应用程序。
4、掌握C#简单数据类型。
5、掌握C#错误和异常处理。
6、掌握C#程序中类的声明和引用。
7、掌握类的字段、属性、方法的声明及其引用。
8、掌握类的继承。
实验环境Visual Studio 2010集成开发环境实验内容1.创建一个抽象的Shape类;2.创建Rectangle 、Triangle两个类并同时继承于Shape;3.在Rectangle类下派生一个Squart类;4.通过Shape基类分别实现Rectangle、Squart、 Triangle、面积的求解;算法描述及实验步骤太原工业学院计算机工程系实验报告调试过程及实验结果实验结果:1002006调试过程出现的问题:未在英文状态下进行编辑;类名称的首先字母未大写;总结通过对此实验的学习,我对多态方法有了更深的认识和了解。
附录using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace my_program{abstract class Shape{public abstract double Area{get;}}using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace my_program{class Rectangle:Shape{ public int Height;public int Width;public override double Area{ get { return Height*Width; } }}}using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace my_program{class Squart :Rectangle{ public int Side;public override double Area{ get{ return Side*Side;}}}}using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace my_program{class Triangle:Shape{ public int side1 = 3;public int side2 = 4;public override double Area{ get{return 0.5 * side1 * side2;}}}}using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace my_program{class Program{static void Main(string[] args){Squart mysquart = new Squart();mysquart.Side = 10;Shape myshape = mysquart;Print(myshape );Rectangle myrectangle = new Rectangle(); myrectangle.Height = 20;myrectangle.Width = 10;myshape = myrectangle;Print(myshape );Triangle mytriangle = new Triangle();mytriangle.side1 = 3;mytriangle.side2 =4;myshape = mytriangle;Print(myshape); }static void Print(Shape a){ Console.WriteLine(a.Area);}}}。
c 多态性实验报告
![c 多态性实验报告](https://img.taocdn.com/s3/m/0eeecd674a35eefdc8d376eeaeaad1f3469311d0.png)
c 多态性实验报告C++多态性实验报告引言:多态性是面向对象编程中的一个重要概念,它允许不同类型的对象对同一消息作出不同的响应。
在C++中,通过虚函数和指针或引用的方式实现多态性。
本实验旨在通过设计一个简单的图形类来演示C++中多态性的应用。
实验过程:1. 设计图形类:首先,我们需要设计一个基类Shape,其中包含一个纯虚函数area()用于计算图形的面积。
然后,派生出两个子类Rectangle和Circle,分别表示矩形和圆形。
这两个子类都需要实现基类中的纯虚函数area()。
2. 实现多态性:在基类Shape中,将area()函数声明为虚函数,以便在派生类中进行重写。
在派生类Rectangle和Circle中,分别重写area()函数,根据具体的图形形状进行面积计算。
3. 创建对象并调用函数:在主函数中,创建Shape、Rectangle和Circle的对象,并通过指针或引用调用它们的area()函数。
由于area()函数在基类中被声明为虚函数,因此在运行时会根据对象的实际类型调用相应的函数。
实验结果:经过实验,我们发现不同类型的图形对象可以通过相同的函数名进行调用,而实际执行的函数却不同。
这就是多态性的体现。
通过多态性,我们可以编写更加灵活和可扩展的代码。
实验分析:多态性的实现依赖于虚函数表(vtable)和虚函数指针(vptr)。
每个带有虚函数的类都会在其内部生成一个虚函数表,用于存储虚函数的地址。
而每个对象都会有一个虚函数指针,指向该对象所属类的虚函数表。
当调用虚函数时,会根据对象的虚函数指针找到对应的虚函数表,并通过偏移量找到实际的函数地址进行调用。
多态性的优势在于代码的可维护性和可扩展性。
通过将函数声明为虚函数,我们可以在基类中定义通用的接口,而具体的实现则由派生类来完成。
这样,当需要添加新的图形类型时,只需要编写新的派生类并重写虚函数即可,而不需要修改基类或其他已有的代码。
此外,多态性还可以实现运行时的动态绑定,即在运行时根据对象的实际类型来决定调用哪个函数。
c#实验报告 实验四 多态性
![c#实验报告 实验四 多态性](https://img.taocdn.com/s3/m/4d74927802768e9951e73880.png)
广州大学学生实验报告开课学院及实验室:机械与电气工程学院、计机楼601B2013年月日有一个ACCESS学生数据库,其中包括本科生表和研究生表,实现从数据库中查找学生并显示相关信息。
在实验三的Staff类、Bachelor类、Postgraduate类的基础上完成。
在Staff类增加find()虚方法。
在Bachelor类增加基类find()虚方法的重载方法。
在Postgraduate类增加基类find()虚方法的重载方法。
Main()要求:1、创建一个人员Staff类对象,创建一个Bachelor类对象,创建一个Postgraduate类对象;2、从键盘输入本科生编号;3、将Bachelor类对象赋给Staff类对象,然后通过Staff类对象在本科生表中查找学生,如果表中有该学生就显示他的信息;4、如果没有则将Postgraduate类对象赋给Staff类对象,然后通过Staff类对象在研究生表中查找学生,如果表中有该学生就显示他的信息;3、如果没有则显示“没有找到该学号的学生”。
实验步骤:1、操作方法如实验一。
创建工程,创建Bachelor类和Postgraduate类,创建测试类,输入Bachelor类和Postgraduate类程序,输入测试类的Main()方法。
2、运行程序。
usingusing System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication4{class Program{static void Main(string[] args){string student_no;Staff boy1 = new Staff();Bachelor boy2 = new Bachelor();Console.WriteLine("请输入编号:");student_no = Console.ReadLine();boy1 = boy2;if (boy1.find(student_no) == true){boy1.StaffCategory = "Bachelor";boy1.Returndata();}else{boy1.StaffCategory = "Postgraduate";boy1 = boy3;if (boy1.find(student_no) == true){//boy1.StaffCategory = "Postgraduate";boy1.Returndata();}elseConsole.WriteLine("请输入编号?:"); Console.WriteLine("没有找到该学号的学生); }Console.ReadLine();}}}System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Data.OleDb;using System.Data.SqlClient;namespace ConsoleApplication4{class Bachelor :Staff{private string Profession;private int Grade;private int Class;public override bool find (string student_no){bool return_val = false;string filename = System.IO.Directory.GetCurrentDirectory() + "\\学生数据库.mdb";if (System.IO.File.Exists(filename)){OleDbConnection dbconn;OleDbDataAdapter da;DataSet ds;string sqlcommand;filename = "provider=microsoft.jet.oledb.4.0;Data Source=" + filename;dbconn = new OleDbConnection(@filename);dbconn.Open();sqlcommand = "select * from 本科生 where 学号='" + student_no + "'";da = new OleDbDataAdapter(@sqlcommand, dbconn);ds = new DataSet();da.Fill(ds);if (ds.Tables[0].Rows.Count > 0){string str;ID = student_no;Name = ds.Tables[0].Rows[0]["姓名"].ToString();College = ds.Tables[0].Rows[0]["学院"].ToString();Profession = ds.Tables[0].Rows[0]["专业"].ToString();str = ds.Tables[0].Rows[0]["年级"].ToString();Grade = Convert.ToInt16(str);str = ds.Tables[0].Rows[0]["班].ToString();Sex = ds.Tables[0].Rows[0]["性别"].ToString();str = ds.Tables[0].Rows[0]["出生日期"].ToString(); Birthday = DateTime.Parse(str);Password = ds.Tables[0].Rows[0]["密码"].ToString(); return_val = true;}else{ID = "";Name = "";Sex = "";Birthday = DateTime.Parse("1-1-1");Password = "";College = "";Profession = "";Grade = 0;Class = 0;}dbconn.Close();dbconn.Dispose();}return return_val;}public Bachelor(): base(){}public Bachelor(string id): base(id){}public Bachelor(string id, string name): base(id, name){public string BachelorProfession {get{return Profession;}set{Profession = value;}}public int BachelorGrade{get{return BachelorGrade;}set{Grade = value;}}public char BachelorClass{get{return BachelorClass;}set{Class = value;}}public override void Returndata()base.Returndata();Console.WriteLine("专业{0}", this.Profession);Console.WriteLine("年级:{0}", this.Grade);Console.WriteLine("班别:{0}", this.Class);}new public void Returndata(string a){if (a == "Profession" || a == "Grade" || a == "Class")switch (a){case"Profession":{Console.WriteLine("专业{0}", this.Profession);break;}case"Grade":{Console.WriteLine("年级:{0}", this.Grade);break;}case"Class":{Console.WriteLine("班别:{0}", this.Class);break;}}elsebase.Returndata(a);}}}using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Data.OleDb;using System.Data.SqlClient;namespace ConsoleApplication4{class Postgraduate : Staff{private string Profession;private int Grade;private string Tutor;public override bool find(string student_no){bool return_val = false;string filename = System.IO.Directory.GetCurrentDirectory() +"\\学生数据库.mdb";if (System.IO.File.Exists(filename)){OleDbConnection dbconn;OleDbDataAdapter da;DataSet ds;string sqlcommand;filename = "provider=microsoft.jet.oledb.4.0;Data Source=" + filename;dbconn = new OleDbConnection(@filename);dbconn.Open();sqlcommand = "select * from 研究生 where 学号?='" + student_no + "'";da = new OleDbDataAdapter(@sqlcommand, dbconn);ds = new DataSet();da.Fill(ds);if (ds.Tables[0].Rows.Count > 0){string str;ID = student_no;Name = ds.Tables[0].Rows[0]["姓名"].ToString();College = ds.Tables[0].Rows[0]["学院"].ToString();Profession = ds.Tables[0].Rows[0]["专业"].ToString();Grade = Convert.ToInt16(str); Tutor = ds.Tables[0].Rows[0]["导师"].ToString();Sex = ds.Tables[0].Rows[0]["性别"].ToString();str = ds.Tables[0].Rows[0]["出生日期"].ToString(); Birthday = DateTime.Parse(str);Password = ds.Tables[0].Rows[0]["密码"].ToString(); return_val = true;}else{ID = "";Name = "";Sex = "";Birthday = DateTime.Parse("1-1-1");Password = "";College = "";Profession = "";Grade = 0;Tutor = "";}dbconn.Close();dbconn.Dispose();}return return_val;}public Postgraduate(): base(){}public Postgraduate(string id): base(id){}public Postgraduate(string id, string name): base(id, name){public string PostgraduateProfession{get{return Profession;}set{Profession = value;}}public int PostgraduateGrade{get{return Grade;}set{Grade = value;}}new public void Returndata(){base.Returndata();Console.WriteLine("专业:{0}", this.Profession);Console.WriteLine("年级:{0}", this.Grade);Console.WriteLine("导师:{0}", this.Tutor);}new public void Returndata(string a){if (a == "Profession" || a == "Grade" || a == "Tutor") switch (a){case"Profession":Console.WriteLine("专业:{0}", this.Profession);break;}case"Grade":{Console.WriteLine("年级:{0}", this.Grade);break;}case"Tutor":{Console.WriteLine("班别:{0}", this.Tutor);break;}}elsebase.Returndata(a);}}}项目名称”栏以上部分统一。
多态性实验报告
![多态性实验报告](https://img.taocdn.com/s3/m/41d1f761af1ffc4ffe47acf1.png)
西安财经学院信息学院《面向对象方法及程序设计》 实验报告实验名称 多态性 实验室 519 实验日期 12.23多态性一、实验目的1. 掌握C++语言源程序的编辑、编译、链接及运行步骤。
2. 掌握C++语言中类和对象的概念和应用。
3. 掌握多态性的概念和使用规则。
二、实验内容1. 利用多态思想写C++程序实现2个长度为5的1维数组的加、减、乘、除运算。
2. 声明一个基类Currency ,其中包含有protected 类型的数据成员Japan 和Europe ,分别代表日元、欧元对美元的汇率。
成员函数set ()用来设置两个数据成员的初值,定义print_exchange()为纯虚函数。
声明Ja 和Eur 分别为Currency 的派生类,其成员函数print_exchange()分别用来计算日元和欧元兑换多少美元。
按照惯例,汇率的表示方式:1美元对话日元116.30,1欧元兑换美元1。
1634.日元和欧元的数量要求可以随机输入。
(汇率固定)三、实验环境 硬件环境:PC 一台软件环境:WIN7操作系统、Microsoft visual c++ 2010四、实验步骤 内容1:姓名 学号 班级 年级 10级 指导教师 李翠#include<iostream>using namespace std;class T{public:T(){a=0;b=0;c=0;d=0;e=0;}T(int i,int j,int k,int l,int m){a=i;b=j;c=k;d=l;e=m;}void get(int &i,int &j,int &k,int &l,int &m) {i=a;j=b;k=c;l=d;m=e;}T operator+(T obj);T operator-(T obj);T operator*(T obj);T operator/(T obj);private:int a,b,c,d,e;};T T::operator+(T obj){T tempobj;tempobj.a=a+obj.a;tempobj.b=b+obj.b;tempobj.c=c+obj.c;tempobj.d=d+obj.d;tempobj.e=e+obj.e;return tempobj;}T T::operator-(T obj){T tempobj;tempobj.a=a-obj.a;tempobj.b=b-obj.b;tempobj.c=c-obj.c;tempobj.d=d-obj.d;tempobj.e=e-obj.e;return tempobj;}T T::operator*(T obj){T tempobj;tempobj.a=a*obj.a;tempobj.b=b*obj.b;tempobj.c=c*obj.c;tempobj.d=d*obj.d;tempobj.e=e*obj.e;return tempobj;}T T::operator/(T obj){T tempobj;tempobj.a=a/obj.a;tempobj.b=b/obj.b;tempobj.c=c/obj.c;tempobj.d=d/obj.d;tempobj.e=e/obj.e;return tempobj;}int main(){T obj1(4,3,5,2,1),obj2(6,4,2,7,4),obj3;int a,b,c,d,e;obj3=obj1+obj2;obj3.get(a,b,c,d,e);(obj2-obj1).get(a,b,c,d,e);cout<<"(obj1-obj2):"<<"a="<<a<<'\t'<<"b="<<b<<'\t'<<"c="<<c<<'\t'<<"d="<<d<<'\ t'<<"e="<<e<<endl<<endl;cout<<"(obj1+obj2):"<<"a="<<a<<'\t'<<"b="<<b<<'\t'<<"c="<<c<<'\t'<<"d="<<d<<'\ t'<<"e="<<e<<endl<<endl;(obj1*obj2).get(a,b,c,d,e);cout<<"(obj1*obj2):"<<"a="<<a<<'\t'<<"b="<<b<<'\t'<<"c="<<c<<'\t'<<"d="<<d<<'\ t'<<"e="<<e<<endl<<endl;(obj2/obj1).get(a,b,c,d,e);cout<<"(obj1/obj2):"<<"a="<<a<<'\t'<<"b="<<b<<'\t'<<"c="<<c<<'\t'<<"d="<<d<<'\ t'<<"e="<<e<<endl<<endl;system("pause");}内容2:#include<iostream>using namespace std;class Currency{protected:float Japan;float Europe;public:Currency(float a,float b){Japan=a;Europe=b;}void set(float a,float b){Japan=a ;Europe=b;}virtual void print_exchange()=0;};class Ja:public Currency{private:float c;public :Ja(float a,float b,float z): Currency(a,b){c=z;}void print_exchange(){cout<<c<<"日元可兑换美元"<<c/116.30<<endl;} };class Eur:public Currency{private:float d;public:Eur(float a,float b,float w): Currency(a,b){d=w;}void print_exchange(){cout<<d<<"欧元可兑换美元"<<d*1.1634<<endl;} };int main(){Currency *p;Ja k(1.0,1.0,100);Eur h(1.0,1.0,100);p=&k;p->print_exchange();p=&h;p->print_exchange();system("pause");return 0;}五、实验结果六、小结通过本次实验,掌握C++语言源程序的编辑、编译、链接及运行步骤,以及C++语言中类和对象的概念和应用,还有多态性的概念和使用规则。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
贵州大学实验报告学院:电子信息学院专业:通信工程班级:
实验内容1. 编写4个重载函数Double(x),返回值为输入参数的两倍;参数类型分别为int、
long、float、double,返回值类型与参数类型一样。
2.请编写一个抽象类Shape,在此基础上派生出类Rectangle和Circle,二者都有计算对象面积的函数GetArea()和计算周长函数GetPerim()。
3.对类Point重载++(自增)、--(自减)运算符。
实验数据1、代码如下:
#include<iostream>
using namespace std;
int Double(int x);
long Double(long x);
float Double(float x);
double Double(double x);
int main()
{ int myInt = 6500;
cout<<Double(myInt)<<endl;
long myLong = 65000;
cout<<Double(myLong)<<endl;
float myFloat = 6.5F;
cout<<Double(myFloat)<<endl;
double myDouble = 6.5e20;
cout<<Double(myDouble)<<endl;}
int Double(int x) { return 2*x;} long Double(long x) { return 2*x;} float Double(float x) { return 2*x;} double Double(double x) { return 2*x;} 运行结果:
2、代码:
#include<iostream>
#define PI 3.1415926;
using namespace std;
class Shape //抽象类的定义
{
public:
virtual double GetArea() = 0; //纯虚函数
cin >> length >> width;
Rectangle rect(length, width);
cout << "面积是:"<< rect.GetArea() << endl<<"周长是:"<<rect.GetPerim()<<endl; double rr;
cout << "输入半径: ";
cin >> rr;
Circle cir(rr);
cout << "面积是:"<<cir.GetArea() << endl<<"周长是:"<<cir.GetPerim()<<endl;
}
运行结果:
3、代码如下:
#include<iostream.h>
class Point
{
public:
Point(int xx,int yy):x(xx),y(yy) {}
void display()const;
Point &operator++();
Point operator++(int);
Point &operator--();
Point operator--(int);
private:
int x,y;
};
void Point::display()const
{
cout<<"当前Point("<<x<<","<<y<<")"<<endl;
}
Point &Point::operator++()
{
x++;
y++;
cout<<"执行x++,y++操作!"<<endl;
return *this;
}
Point Point::operator++(int)
{
cout<<"执行++x,++y操作!"<<endl;
return Point(++x,++y);
}
Point &Point::operator--(){x--;y--;
cout<<"执行x--,y--操作!"<<endl; return *this;
}
Point Point::operator--(int)
{cout<<"执行--x,--y操作!"<<endl; return Point(--x,--y);
}
int main()
{
int x,y;
cout<<"Input x&y:";
cin>>x>>y;
Point point1(x,y);
point1.display();point1++;
point1.display();++point1;
point1.display();point1--;
point1.display();--point1;
point1.display();return 0;
}
运行结果:
注:各学院可根据教学需要对以上栏木进行增减。
表格内容可根据内容扩充。