编程时,我们想要将两个int类型相加,大家都知道要怎么做,但当我定义了自己的数据类型时,这些数据类型要怎么相加呢?例如两个类要怎么相加并输出我们想要的结果呢?
这就要用到c++中的重载操作符了,c++中允许我们定义相对应的类的操作符,在这些操作符中我们通过一些内置数据类型的操作(如int型的相加)来实现我们想要的功能,前几天看过一个分数的四则运算的程序,凭着记忆写下来,咳咳,就只有四则运算啦。
#include<iostream>
#include<string>
#include<math.h>
using namespace std;
class fraction //分数的类
{
public:
int above; //分子
int blow; //分母
};
int simplify(int a,int b)
{
if(b==0)return a;
else return simplify(b,a%b); //用递归求出最大公约数
}
istream& operator >> (istream& in,fraction& s) //输入操作符的重载
{
in >> s.above;
getchar(); //接收"/"
in >> s.blow;
return in; //记得要有返回值
}
ostream& operator << (ostream& out,const fraction& s) //输出操作符
{
if(s.above == 0) out <<"0";
else if(s.blow==1)out << s.above;
else out << s.above << "/" << s.blow;
return out;
}
fraction operator+(const fraction& x, const fraction& y) //加号
{
fraction z;
int a,b,m=1;
a=x.blow*y.above+x.above*y.blow;
b=x.blow*y.blow;
if(a!=0)
m = a<b ? simplify (b,a) : simplify(a,b); //根据a和b的大小有不同
z.above = a/m;z.blow = b/m;
return z;
}
fraction operator-(const fraction& x, const fraction& y)
{
fraction z;
int a,b,m=1;
a=x.blow*y.above-x.above*y.blow;
b=x.blow*y.blow;
if(a!=0)
m = a<b ? simplify (b,a) : simplify(a,b);
z.above = a/m;z.blow = b/m;
return z;
}
fraction operator*(const fraction& x, const fraction& y)
{
fraction z;
int a,b,m=1;
a = x.above*y.above;
b = x.blow*y.blow;
if(a!=0)
m = a<b ? simplify (b,a) : simplify(a,b);
z.above = a/m;z.blow = b/m;
return z;
}
fraction operator/(const fraction& x, const fraction& y)
{
fraction z;
int a,b,m=1;
if(y.above==0) //若除数为0,抛出异常
throw exception ("error blow!!");
else
{
a = x.above * y.blow;
b = x.blow * y.above;
if(a!=0)
m = a<b ? simplify (b,a) : simplify(a,b);
z.above = a/m;z.blow = b/m;
}
return z;
}
int main()
{
fraction x,y;
char ob;
cout << "请用x/y + x/y的方式输入想要进行运算的分数" <<endl;
cin >> x >> ob >> y;
cout << "结果是:" << endl;
switch(ob)
{
case '+' : cout << x+y << endl; break;
case '-' : cout << x-y << endl; break;
case '*' : cout << x*y << endl; break;
case '/' : cout << x/y << endl;
}
system("pause");
}
感觉重要的是操作符内部的算法啦!