c++运算符重载不改变运算符的优先级和结合性。
格式为 返回类型 operator 运算符(参数列表)
输出结果
#include <iostream>
#include <string>
struct vector2
{
float x, y;
vector2(float x, float y)
:x(x), y(y) {}
vector2 add(const vector2& other) const
{
return vector2(x + other.x, y + other.y);
}
vector2 operator+ (const vector2& other) const
{
return add(other);
}
vector2 multiply(const vector2& other) const
{
return vector2(x * other.x, y * other.y);
}
vector2 operator* (const vector2& other) const
{
return multiply(other);
}
};
std::ostream& operator<< (std::ostream& stream, const vector2& other)
{
stream << other.x << ", " << other.y ;
return stream;
}
void Log(vector2 message)
{
std::cout << message.x << ", " << message.y << std::endl;
}
int main()
{
vector2 speed(1.0f, 1.0f);
vector2 position(2.0f, 2.0f);
vector2 powerup(3.0f, 3.0f);
vector2 result1 = position.add(speed.multiply(powerup));
vector2 result2 = position + speed * powerup;
std::cout << "Function Log" << std::endl;
Log(result1);
Log(result2);
std::cout << "Operator << " << std::endl;
std::cout << result1 << std::endl;
std::cout << result2 << std::endl;
std::cin.get();
return 0;
}