以代码为例,重载了<< >> = + - * /
/************************************************************************/
/* 功能:分数类 */
/* 描述:支持+ - * / */
/************************************************************************/
#include <iostream>
using namespace std;
类申明//
class Fraction{
private:
int m;
int z;
public:
Fraction(int z = 1, int m = 1):z(z), m(m){} //默认构造函数
Fraction(const Fraction & F):z(F.z), m(F.m){} //拷贝构造函数
~Fraction(){}
//(重载类型一)友元函数:友元函数中可以调用该类的私有变量
friend istream& operator>>(istream& in, Fraction & F);
friend ostream& operator<<(ostream& out, Fraction & F);
//(重载类型二)使用引用做返回值:可以像cout与cin一样流操作
Fraction & operator =( const Fraction & f);
//(重载类型三) 一般重载:重载了+-*/,重点是学习重载,所以不考虑算法
Fraction operator +( const Fraction & f);
Fraction operator -( const Fraction & f);
Fraction operator *( const Fraction & f);
Fraction operator /( const Fraction & f);
};
类的实现//
Fraction& Fraction::operator=(const Fraction & f)
{
this->z = f.z;
this->m = f.m;
return *this;
}
Fraction Fraction::operator +( const Fraction & f)
{
Fraction temp;
temp.z = this->z + f.z;
temp.m = this->m + f.m;
return temp;
}
Fraction Fraction::operator -( const Fraction & f)
{
Fraction temp;
temp.z = this->z - f.z;
temp.m = this->m - f.m;
return temp;
}
Fraction Fraction::operator *( const Fraction & f)
{
Fraction temp;
temp.z = this->z * f.z;
temp.m = this->m * f.m;
return temp;
}
Fraction Fraction::operator /( const Fraction & f)
{
Fraction temp;
temp.z = this->z / f.z;
temp.m = this->m / f.m;
return temp;
}
//全局函数
ostream& operator<<(ostream& out, Fraction & F)
{
out<<F.z<<"/"<<F.m;
return out;
}
istream& operator >>(istream& in, Fraction & F)
{
char c;
in>>F.z>>c>>F.m;
if (c == '/')
{
return in;
}else{
cout<<"输入错误"<<endl;
F.m = 1;
F.z = 1;
return in;
}
}
测试函数//
int main()
{
Fraction a,b,c,d,e,f,g(2,3);
cout<<"(test << )Please enter a fraction: a = ";
cin>>a;
b = a;
cout<<"(test >> = ) b = a : b = "<<b<<endl;
c = a + b;
cout<<"(test >> = +) c = a + b : c = "<<c<<endl;
d = c - b;
cout<<"(test >> = -) d = c - b : d = "<<d<<endl;
e = a * b;
cout<<"(test >> = *) e = a * b : e = "<<e<<endl;
f = e / g;
cout<<"(test >> = /) f = e / (2/3);: f = "<<f<<endl;
system("pause");
return 0;
}