实验六_运算符重载

  • 格式:doc
  • 大小:49.50 KB
  • 文档页数:4

南昌航空大学实验报告
年月日
课程名称:面向对象程序设计实验名称:运算符重载
班级:学生姓名:学号:
指导教师评定: 签名:
1、实验目的
·学习掌握重定义与类有关的运算符。

·把握重载运算符的时机。

·学习掌握把一个类对象转换为另一个类对象。

·学习掌握重载为成员与友元的区别及其带参数的情况。

·学习掌握值返回与引用返回的区别及应用时机。

2、实验内容
(1)
生成一个表示复数的类FS。

复数的实部sb和虚部xb作为其数据成员。

提供成员函数disp()显示复数(格式:-3+5i或6-2i),重载“+”、“-”为FS类的成员函数,用来计算两个复数的和、差。

思路导航:
①定义类,设计构造函数和显示函数print();
②重载运算符“+”、“-”为类FS的成员函数。

③实例化FS类的2个对象,并利用重载的运算符对其进行计算。

另外,根据上述定义,试将上述的运算符重载成员函数改写成友元函数。

#include <iostream.h>
class FS{
double sb,xb;
public:
FS(double a=0,double b=0);
FS &operator + (FS &);
FS &operator - (FS &);
void print();
};
FS::FS(double a,double b){
sb = a;
xb = b;
}
FS& FS::operator + (FS &b){
FS p;
p.sb = sb + b.sb ;
p.xb = xb + b.xb ;
return p;
}
FS& FS::operator - (FS &b){
FS p;
p.sb = sb - b.sb ;
p.xb = xb - b.xb ;
return p;
}
void FS::print (){
if(xb > 0)
cout<<sb<<"+"<<xb<<"i";
else
cout<<sb<<xb<<"i";
}
void main(){
FS a(-8,3),b(7,-4);
FS c1;c1=a+b;
a.print();cout<<" + ";
b.print();cout<<" = ";c1.print();cout<<endl;
FS c2;c2=a-b;
a.print();cout<<" - ";
b.print();cout<<" = ";c2.print();cout<<endl;
}
//-------------------------运算符重载为友元函数--------------------------- #include <iostream.h>
class FS{
double sb,xb;
public:
FS(double a=0,double b=0);
friend FS operator+ (FS &,FS &);
friend FS operator- (FS &,FS &);
void print();
};
FS::FS(double a,double b){
sb = a;
xb = b;
}
FS operator+ (FS &x,FS &y){
FS p;
p.sb = x.sb + y.sb ;
p.xb = x.xb + y.xb ;
return p;
}
FS operator- (FS &x,FS &y){
FS p;
p.sb = x.sb - y.sb ;
p.xb = x.xb - y.xb ;
return p;
}
void FS::print (){
if(xb > 0)
cout<<sb<<"+"<<xb<<"i";
else
cout<<sb<<xb<<"i";
}
int main(){
FS a(8,3),b(7,-14);
FS c1;c1=a+b;
a.print();cout<<" + ";
b.print();cout<<" = ";c1.print();cout<<endl;
FS c2;c2=a-b;
a.print();cout<<" - ";
b.print();cout<<" = ";c2.print();cout<<endl;
return 0;
}
(2)
编写一个时间类,实现时间的加、减、读和输出:
//class.h
class Time{
public:
Time(){}
void SetTime();
void Display();
Time operator + (Time &a);
Time operator - (Time &a);
private:
int hour,minute,second;
};
//function.cpp
#include <iostream.h>
#include "class.h"
void Time::SetTime(){
cout<<"小时: ";cin>>hour;
cout<<"分钟: ";cin>>minute;
cout<<"秒: ";cin>>second;
}
void Time::Display(){
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
Time Time::operator + (Time &a){
Time p;
p.hour = hour + a.hour ;
p.minute = minute + a.minute ;
p.second = second + a.second ;
return p;
}
Time Time::operator - (Time &a){
Time p;
p.hour = hour - a.hour ;
p.minute = minute - a.minute ;
p.second = second - a.second ;
return p;
}
//overload.cpp
#include <iostream.h>
#include "class.h"
void main(){
Time a,b,c;
cout<<"请输入A的时间:"<<endl;a.SetTime();
cout<<"请输入B的时间:"<<endl;b.SetTime();
cout<<"A的时间为:";a.Display();
cout<<"B的时间为:";b.Display();
cout<<"c=a+b=";c=a+b;c.Display();
cout<<endl<<"c=a-b=";c=a-b;c.Display();
}
3、实验结果。