实验四-运算符重载-实验报告.doc
文本预览下载声明
实验报告
实验目的:掌握运算符重载的语法要点,学会运算符重载的编程方法。
实验内容:
(1)先读程序,预测程序的输出结果,再运行程序验证程序的输出。用友元重载方式重新编写次程序。
#include iostream.h
class Vector
{ public:
Vector(){}
Vector(int i,int j) {x=i;y=j;}
friend Vector operator+=(Vector v1,Vector v2)
{ v1.x+=v2.x;
v1.y+=v2.y;
return v1;
}
Vector operator-=(Vector v)
{ Vector temp;
temp.x=x-v.x;
temp.y=y-v.y;
return temp;
}
void display()
{ cout(x,y)endl;}
private:
int x,y;
};
void main()
{
Vector v1(1,2),v2(3,4),v3,v4;
v3=v1+=v2;
v4=v1-=v2;
coutv1=;
v1.display();
coutv2=;
v2.display();
coutv3=;
v3.display();
coutv4=;
v4.display();
}
运行结果:
v1=(1,2)
v2=(3,4)
v3=(4,6)
v4=(-2,-2)
Press any key to continue
用友元重载方式重新编写次程序:
#include iostream
using namespace std;
class Vector
{
public:
Vector(int i = 0,int j = 0)
{
x=i;
y=j;
}
friend Vector operator+=(Vector v1,Vector v2)
{
v1.x+=v2.x;
v1.y+=v2.y;
return v1;
}
friend Vector operator-=(Vector v1,Vector v2)
{
v1.x=v1.x-v2.x;
v1.y=v1.y-v2.y;
return Vector( v1.x, v1.y);
}
void display()
{
cout(x,y)endl;
}
private:
int x,y;
};
void main()
{
Vector v1(1,2),v2(3,4),v3,v4;
v3 = v1+=v2;
v4 = v1-=v2;
coutv1=; v1.display();//1,2
coutv2=; v2.display();//3,4
coutv3=; v3.display();//4,6
coutv4=; v4.display();//1,2
}
运行结果:
v1=(1,2)
v2=(3,4)
v3=(4,6)
v4=(-2,-2)
Press any key to continue
(2)定义一个有理数类,重载比较运算符.写一个完整的程序,进行数据成员的设置和输出。
#includeiostream.h
class rational
{
private:
long denom,den;
public:
rational(long num=0, long denom1=1)
{
denom=num;
den=denom1;
}
int operator(rational r) const
{
double x,y;
x=denom*1.0/den;
y=r.denom*1.0/r.den;
if(xy)
return 1;
return 0;
}
int operator=(rational r) const
{
double x,y;
x=denom*1.0/den;
y=r.denom*1.0/r.den;
if(x=y)
return 1;
return 0;
}
int operator==(rational r) const
{
double x,y;
x=denom*1.0/den;
y=r.denom*1.0/r.den;
if(x==y)
return 1;
return 0;
}
int operator!=(rational r) const
{
double x,y;
x=denom*1.0/den;
y=r.denom*1.0/r.den;
if(x!=y)
ret
显示全部