运算符重载
运算符重载规则
- 符合语法规则
- 不能创建新的运算符
- 不能重载
.
,.*
,?:
- 重载要保证原有基本语义不变。
运算符重载实际上就是函数的重载。
运算符重载形式
1.成员函数重载运算符
<返回值类型> operator<运算符>(参数)
参数个数与运算符的操作数个数有关。且注意,每个非静态成员函数带有自引用参数 this 指针。 所以成员函数重载运算符需要的参数的个数总比它的操作数少一个。
class Point
{
public:
Point(int x = 0, int y = 0)
{
_x = x;
_y = y;
}
~Point()
{
;// cout<<"destructor"<<endl;
}
Point operator+(Point pt);
void printPoint()
{
cout<<"["<<_x<<","<<_y<<"]"<<endl;
}
private:
int _x;
int _y;
};
Point Point::operator+(Point pt)
{
Point temp;
temp._x = this->_x + pt._x;
temp._y = this->_y + pt._y;
return temp;
}
int main()
{
Point p1(1,2);
Point p2(1,4);
p1 = p1 + p2;
p1.printPoint();
return 0;
}
2.友元函数重载运算符
friend <返回值类型> operator<运算符>(参数)
友元函数不是类的成员,没有this指针,所以参数必须显示声名。友元函数运算符重载需要的参数个数与操作数一样多。
class Point
{
public:
Point(int x = 0, int y = 0)
{
_x = x;
_y = y;
}
~Point()
{
;// cout<<"destructor"<<endl;
}
friend Point operator+(Point pt1,Point pt2);
void printPoint()
{
cout<<"["<<_x<<","<<_y<<"]"<<endl;
}
private:
int _x;
int _y;
};
Point operator+(Point pt1,Point pt2)
{
Point temp;
temp._x = pt1._x + pt2._x;
temp._y = pt2._y + pt2._y;
return temp;
}
int main()
{
Point p1(1,2);
Point p2(1,4);
p1 = p1 + p2;
p1.printPoint();
return 0;
}
友元函数重载运算符有一定限制:
- 赋值运算符不能用友元函数重载,
-=,+=
运算符也不可以。 - 友元函数不能重载
(),[],->
- 重载
++ 和 --
运算符是友元函数需要引用参数。(如下面的单目运算符重载)
单目运算符重载
举例: ++和- - 的重载
1. 用成员函数重载
前缀++:
<返回类型>::operator++();
后缀++
<返回类型>::operator++(int);
int 参数表明调用该函数时运算符"++"应该放在操作数的后面,且参数本身没有被用到。
class Point
{
public:
Point(int x = 0, int y = 0)
{
_x = x;
_y = y;
}
~Point()
{
;// cout<<"destructor"<<endl;
}
friend Point operator+(Point pt1,Point pt2int);
Point operator++(); //前缀
Point operator++(int); //后缀
void printPoint()
{
cout<<"["<<_x<<","<<_y<<"]"<<endl;
}
private:
int _x;
int _y;
};
Point operator+(Point pt1,Point pt2)
{
Point temp;
temp._x = pt1._x + pt2._x;
temp._y = pt2._y + pt2._y;
return temp;
}
Point Point::operator++()
{
_x++;
_y++;
return *this;
}
Point Point::operator++(int)
{
Point temp;
temp._x = _x++;
temp._y = _y++;
return temp;
}
int main()
{
Point p1(1,2);
Point p2(1,4);
Point p3;
p1 = p1 + p2;
p1.printPoint();
p3 = ++p1;
p1.printPoint();
p3.printPoint();
p3 = p2++;
p2.printPoint();
p3.printPoint();
return 0;
}
1. 用友元函数重载
由于友元函数没有this指针,要修改操作数的值,就需要使用引用传参。
前缀++:
<返回类型>::operator++(<类名>&);
后缀++
<返回类型>::operator++(<类名>&,int);