重载操作符问题

来源:百度知道 编辑:UC知道 时间:2024/05/21 07:01:52
我在百度上看到一个重载操作符的网址
#include <iostream>
using namespace std;
class Point;//要加声明
Point operator+(Point &a,Point &b);//要加声明
//##############################################
class Point
{
public:
int x,y;
void set(int a,int b)
{
x=a,y=b;
}
void print() const
{
cout<<"("<<x<<","<<y<<")\n";
}
friend Point operator+(const Point &a,const Point &b);
friend Point add( Point &a, Point &b);
};
//---------------------------------------------------------
Point operator+( Point &a,Point &b)
{
Point s;
s.set(a.x+b.x,a.y+b.y);
return s;
}//---------------------------------------------------------
Point add( Point &a, Point &b)
{
Point s;
s.set(a.x+b.x,a.y+b.y);
return s;
}//===========================================================
vo

比方说你重载了+,-,*,/
你要做这么一个运算:
a*(b*c/d+e)-b
如果你重载了+,-,*,/,像上面那么写就可以了!

否则你就不得不写成:

tmp = b.mul(c);
tmp = tmp.div(d);
tmp = tmp.add(e);
tmp = tmp.mul(a);
tmp = tmp.sub(b);
当然这是假设add,sub,mul,div分别是加减乘除。

现在明白了吧?

重载操作符的最大好处就是写起来方便,形像。