文章转自 https://blog.csdn.net/u012043391/article/details/76168625
C++运算符重载在自定义类中经常会用到,比如当我们自定义一个点类Point,想对Point类对象进行加减比较判断等操作时,就需要对相应运算符进行重载。
以operator+为例,通常直观的感觉操作数就是应该有两个,写法如下:
Point operator+(const Point &p1,const Point &p2)const;//(会报错)
如果按照上边的写法,写两个输入参数的话,就会报错如下:
这是为什么呢?原来,成员函数有this指针,对象本身的成员数据作为一个加数,看一下下面这个例子就很清楚了:
class Point1 {
int x;
int y;
Point1() : x(0), y(0) {}
Point1(int _x, int _y) : x(_x), y(_y) {}
Point1 operator+(const Point1 &t) const{
Point1 temp;
temp.x = this->x + t.x;
temp.y = this->y + t.y;
return temp;
}
};
那么,可不可以写两个参数呢?完全可以呀,只要把函数声明成友元就可以了,友元函数没有this指针,所以参数会多一个,写法参考如下:
class Point2 {
int x;
int y;
Point2() : x(0), y(0) {}
Point2(int _x, int _y) : x(_x), y(_y) {}
friend Point2 operator+(const Point2 &t1, const Point2 &t2) {
Point2 temp;
temp.x = t1.x + t2.x;
temp.y = t1.y + t2.y;
return temp;
}
};
那么总结一下,运算符重载其实有两种方法:成员函数和友元函数,成员函数一参数,友元函数两参数,成员函数声明结尾有const,友元函数声明结尾无const(非成员函数上不允许使用类型限定符)