运算符重载
c++引入运算符重载机制目的为了类类型(枚举类型)模仿内置类型运算符操作,因此运算符重载必须确保至少一个参数为类类型(枚举类型),且必须是对象形式,而非指针(引用)形式:
- 运算符重载机制不能改变运算符的操作数个数
- 运算符重载机制不能改变运算符的优先级
- 运算符重载机制不能改变现有类型(内置类型&复合类型)支持的运算符含义,如果重载两个整型的加运算符,改变两个整型的加运算符含义,则编译系统会混乱不堪
- 运算符重载本质还是函数,只是函数名特别的函数,函数名中包含operator和运算符,因此运算符重载函数返回值可为void,且可重载(运算符重载函数形参个数固定,只能通过形参类型不同重载)
enum运算符重载
enum EPoint5
{
ZERO,
ONE,
TWO,
THREE,
FOUR,
};
EPoint5 operator+(EPoint5 point1, int point2)
{
int ret = ((int)point1 + point2) % 5;
cout << "operator+(EPoint5, int) = " << ret << endl;
switch(ret)
{
case 0:
return ZERO;
case 1:
return ONE;
case 2:
return TWO;
case 3:
return THREE;
case 4:
return FOUR;
}
return ZERO;
}
EPoint5 operator+(int point1, EPoint5 point2)
{
int ret = (point1 + (int)point2) % 5;
cout << "operator+(int, EPoint5) = " << ret << endl;
switch(ret)
{
case 0:
return ZERO;
case 1:
return ONE;
case 2:
return TWO;
case 3:
return THREE;
case 4:
return FOUR;
}
return ZERO;
}
EPoint5 operator+(EPoint5 point1, EPoint5 point2)
{
int ret = ((int)point1 + (int)point2) % 5;
cout << "operator+(EPoint, EPoint5) = " << ret << endl;
switch(ret)
{
case 0:
return ZERO;
case 1:
return ONE;
case 2:
return TWO;
case 3:
return THREE;
case 4:
return FOUR;
}
return ZERO;
}
void enum_op_overload()
{
EPoint5 point = THREE;
point + 3 + 8;
3 + point + 8;
point + point;
operator+(point, 3);
operator+(3, point);
operator+(point, point);
}
output:
operator+(EPoint5, int) = 1
operator+(EPoint5, int) = 4
operator+(int, EPoint5) = 1
operator+(EPoint5, int) = 4
operator+(EPoint, EPoint5) = 1
operator+(EPoint5, int) = 1
operator+(int, EPoint5) = 1
operator+(EPoint, EPoint5) = 1
class运算符重载
class CPoint
{
public:
CPoint(int point) : mPoint(point) {}
public:
int mPoint;
};
CPoint operator+(CPoint point1, int point2)
{
int ret = (point1.mPoint + point2) % 5;
cout << "operator+(CPoint, int) = " << ret << endl;
return CPoint(ret);
}
CPoint operator+(int point1, CPoint point2)
{
int ret = (point1 + point2.mPoint) % 5;
cout << "operator+(int, CPoint) = " << ret << endl;
return CPoint(ret);
}
CPoint operator+(CPoint point1, CPoint point2)
{
int ret = (point1.mPoint + point2.mPoint) % 5;
cout << "operator+(CPoint, CPoint) = " << ret << endl;
return CPoint(ret);
}
void class_op_overload()
{
CPoint point(3);
point + 3 + 8;
3 + point + 8;
point + point;
operator+(point, 3);
operator+(3, point);
operator+(point, point);
}
output:
operator+(CPoint, int) = 1
operator+(CPoint, int) = 4
operator+(int, CPoint) = 1
operator+(CPoint, int) = 4
operator+(CPoint, CPoint) = 1
operator+(CPoint, int) = 1
operator+(int, CPoint) = 1
operator+(CPoint, CPoint) = 1
总结
支持重载的运算符:
算术操作符:+,-,*,/,%
复合算术操作符:
位操作符
复合