实验七多态性
一、实验目的
- 掌握运算符重载的方法;
- 掌握使用虚函数的继承实现动态多态性。
- 掌握纯虚函数及抽象类的使用。
二、实验内容
- 设计复数类Complex(请参照教材例题8-1的设计),实现运算符重载。 要求:
(1)重载运算符“+”和“*”,使之分别能用于复数相加和相乘。(30分)
(2)重载运算符“<<”,使得复数对象能够使用“<<”运算符输出。(15分)
class Complex{
public:
Complex (int,int); //构造函数
Complex (const Complex &c); //复制构造函数
~ Complex (); //析构函数
Complex operator + (Complex &m); //重载 + 运算符
Complex operator * (Complex &m); //重载 * 运算符
friend ostream &operator << (ostream &out,
const Complex &m); //重载"<<"运算符
int getReal() const {return real;} //得到复数实部
int getImag() const {return imag;} //得到复数虚部
private:
int real,imag; //复数的实部与虚部
};
int main(void){
Complex c1(5,4),c3(3,10),c3; //定义复数类的对象
c3 = c1 + c2;
cout << “c3 = “ << c3;
Complex c4 = c1 * c2 ;
Cout << “c4 = “ << c4;
return 0;
}
- 定义抽象类Geometry;在此基础上派生出类Rectangle和Circle.二者都有计算对象周长函数double getPerim() 计算面积的函数double 两者对象的周长和面积,测试动态多态性。可以在主函数中使用以下语句来测试类(50分)。
int main(){
Rectangle x1(2,3);
cout<<"Rectangle:"<<endl;
fun(&x1);
Circle y1(5);
cout<<"Circle:"<<endl;
fun(&y1);
return 0;
}
##三、实验步骤及结果
- 代码:
#include <iostream>
using namespace std;
class Complex{
public:
Complex (int r=0,int i=0):real(r),imag(i){}
Complex (const Complex &c);
~ Complex (){}
Complex operator+(Complex &m);
Complex operator*(Complex &m);
friend ostream &operator << (ostream &out,const Complex &m);
int getReal() const {return real;}
int getImag() const {return imag;}
private:
int real,imag;
};
Complex::Complex(const Complex &c){
real=c.real;
imag=c.imag;
}
Complex Complex::operator+(Complex &m){
return Complex(this->real+m.real,this->imag+m.imag);
}
Complex Complex::operator*(Complex &m){
return Complex(this->real*m.real,this->imag*m.imag);
}
ostream &operator << (ostream &out,const Complex &m){
cout<<"("<<m.real<<","<<m.imag<<")";
}
int main(void){
Complex c1(5,4),c2(3,10),c3;
c3 = c1 + c2;
cout<<"c3 = "<<c3<<endl;
Complex c4 = c1 * c2 ;
cout<<"c4 = "<<c4<<endl;
return 0;
}
运行结果:
- 代码:
#include <iostream>
using namespace std;
class Geometry{
public:
Geometry(){
}
};
class Rectangle:public Geometry{
public:
Rectangle(double x0,double y0){
x=x0;y=y0;
}
double getPerim(){
return 2*(x+y);
}
double getArea(){
return x*y;
}
private:
double x,y;
};
class Circle:public Geometry{
public:
Circle(double r0){
r=r0;
}
double getPerim(){
return r*3.14*2;
}
double getArea(){
return r*r*3.14;
}
private:
double r;
};
void fun(Circle &p){
cout<<"周长是:"<<p.getPerim()<<"\t";
cout<<"面积是:"<<p.getArea()<<endl;
}
void fun(Rectangle &p){
cout<<"周长是:"<<p.getPerim()<<"\t";
cout<<"面积是:"<<p.getArea()<<endl;
}
int main(){
Rectangle x1(2,3);
cout<<"Rectangle:"<<endl;
fun(x1);
Circle y1(5);
cout<<"Circle:"<<endl;
fun(y1);
return 0;
}
运行结果:
四、实验小结(5分)
问题与解决办法:做实验时,忘记了析构函数的书写方式,一个~ 写成了两个~~,通过百度复习了其正确的书写方式。
心得体会:通过本次实验,进一步加深了对运算符重载等知识的学习,同时也复习了前面的构造函数等。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)