在C++中运算符不仅包括+、-、*、/,还有<<、new、delete、逗号(,)、()、[]等实际上也是运算符。
C++中运算符可以被重载,在C#中部分可以,Java中则完全不可以。
重载运算符关键字:operator。operator跟上要重载的运算符,如oprator+重载+号、oprator*重载*号等等。
演示代码部分:
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 oprator+ (const Vector2 &other) const //重载+
{
return Add(other);
}
Vector2 Mulitply(const Vector2 &other) const
{
return Vector2(x * other.x, y * other.y);
}
Vector2 oprator*(const Vector2 &other) const //重载*
{
return Mulitply(other);
}
};
std::ostream &oprator<<(std::stream &stream, const Vector2 &other) //重载<<运算符
{
stream << other.x << ", " << other.y ;
return stream;
}
int main()
{
Vector2 position(4.0f, 4.0f);
Vector2 speed(0.5f, 1.5f);
Vector2 powerup(1.1f, 1.1f);
Vector2 result1 = position.add(speed.mulitply(powerup)); //传统方法,用函数实现加法乘法
Vector2 result2 = position + speed * powerup; //通过运算符重载实现加法乘法
std::cout << result2 <<std::endl; //需要重载<<运算符
}