运算符重载
运算符重载也是简化代码的一个方式。例如如下代码,向量类的和与积运算在符号+和*是没有定义过的,但是通过运算符重载可以让+和*实现向量类之间的运算。
另外,如果不重载运算符,类或者其他地方就要写相关的函数(add、mutiply)来实现功能,在使用函数的时候名称会极其复杂(例如a1+a2*a3必须写成a1.add(a2.mutiply(a3)),不利于理解)
如下代码实现了+,*,==,!=,<<的重载。
#include <iostream>
using namespace std;
struct Vector2
{
float x, y;
Vector2(float x, float y) : x(x), y(y) {}
Vector2 operator+(const Vector2& other) const
{
return Vector2(x + other.x, y + other.y);
}
Vector2 operator*(const Vector2& other) const
{
return Vector2(x * other.x, y * other.y);
}
bool operator==(const Vector2& other) const
{
return x == other.x and y == other.y;
}
bool operator!=(const Vector2& other) const
{
return !(*this == other);
}
};
// 输出流重载不属于类
ostream& operator<<(ostream& stream, const Vector2& other)
{
stream << other.x << ',' << other.y;
return stream;
}
int main()
{
Vector2 v1(1, 2);
Vector2 v2(2, 2);
Vector2 result1 = v1 * v2 + v1;
if (v1 != v2)
cout << result1 << endl;
}
重载的写法与普通函数一样,注意返回值与参数的类型,函数名就是operator<运算符>,函数体实现功能。