课程首页地址:https://blog.51cto.com/sxhelijian/2813705
本周目标是:(1)学会定义类中双目和单目运算符的重载函数;(2)学会使用类的成员函数和友元函数实现运算符的重载
【项目1-实现复数类中的运算符重载】定义一个复数类重载运算符+、-、*、/,使之能用于复数的加减乘除。
(1)任务一:请用类的成员函数完成运算符的重载;
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;
};
//下面定义成员函数
//下面定义用于测试的main()函数
int main()
{
Complex c1(3,4),c2(5,-10),c3;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
c3=c1+c2;
cout<<"c1+c2=";
c3.display();
c3=c1-c2;
cout<<"c1-c2=";
c3.display();
c3=c1*c2;
cout<<"c1*c2=";
c3.display();
c3=c1/c2;
cout<<"c1/c2=";
c3.display();
return 0;
}
(2)任务二:请用类的友元函数,而不是成员函数,完成上面提及的运算符的重载;
(3)任务三:在方案二的基础上,扩展+、-、*、/运算符的功能,使之能与double型数据进行运算。设Complex c; double d; c?d和d?c的结果为“将d视为实部为d的复数同c运算”的结果(其中?为+、-、*、/之一)。另外,再定义一目运算符 -,-c相当于0-c。
【项目2-Time类中的运算符重载】实现Time类中的运算符重载
#include <iostream>
using namespace std;
class CTime
{private:
unsigned short int hour; // 时
unsigned short int minute; // 分
unsigned short int second; // 秒
public:
CTime(int h=0,int m=0,int s=0);
void setTime(int h,int m,int s);
void display();
//比较运算符(二目)的重载
bool operator > (CTime &t);
bool operator < (CTime &t);
bool operator >= (CTime &t);
bool operator <= (CTime &t);
bool operator == (CTime &t);
bool operator != (CTime &t);
//二目运算符的重载
CTime operator+(CTime &c);//返回c所规定的时、分、秒后的时间,例t1(8,20,25),t2(11,20,50),t1+t2为:41:15
CTime operator-(CTime &c);//对照+理解
CTime operator+(int s);//返回s秒后的时间
CTime operator-(int s);//返回s秒前的时间
//一目运算符的重载
CTime operator++( int);//后置++,下一秒
CTime operator++();//前置++,下一秒,前置与后置返回值不一样
CTime operator--( int);//后置--,前一秒
CTime operator--();//前置--,前一秒
//赋值运算符的重载
CTime operator+=(CTime &c);
CTime operator-=(CTime &c);
CTime operator+=(int s);
CTime operator-=(int s);
};
//下面实现所有的运算符重载代码。
//为简化编程,请注意通过调用已有函数,利用好各函数之间的关系
int main()
{
CTime t1(8,20,25),t2(11,20,50),t;
cout<<"t1为:";
t1.display();
cout<<"t2为:";
t2.display();
cout<<"下面比较两个时间大小:\n";
if (t1>t2) cout<<"t1>t2"<<endl;
if (t1<t2) cout<<"t1<t2"<<endl;
if (t1==t2) cout<<"t1=t2"<<endl;
if (t1!=t2) cout<<"t1≠t2"<<endl;
if (t1>=t2) cout<<"t1≥t2"<<endl;
if (t1<=t2) cout<<"t1≤t2"<<endl;
cout<<endl;
//下面自行设计对其他运算符的重载的测试
……
}
【项目3-分数类中的运算符重载】实现分数类中的运算符重载,在分数类中可以完成分数的加减乘除(运算后再化简)、求反、比较(6种关系)的运算。可以从第5周项目2的代码开始工作。
class CFraction
{private:
int nume; // 分子
int deno; // 分母
public:
//构造函数及运算符重载的函数声明
};
//重载函数的实现及用于测试的main()函数
【项目4-分数类和整型数的四则运算】在项目3的基础上拓展。分数类中的对象可以和整型数进行四则运算,且运算符合交换律。例如:CFraction a(1,3),b; int i=2; 可以完成b=a+i;。同样,可以完成i+a, 45+a, a*27, 5/a等各种运算。
【项目5-扩充String类】在P324基础上,在String类中增加一个数据成员len表示字符串中字任个数,然后构造String类的相关运算。这些运算可以包括:s1 + s2用于两个字符串的连接;s1 - s2用于将s1的尾部空格和s2的前导空格去除后的连接;s1*n的结果为将s1中的字符重复n次;s1/s2表示在s1中删除所有与s2相同的子串。这些运算本身并无统一的规范,多想一些字符串上的操作,利用运算符的重载实现之。