OPERATORS & OPERATOR OVERLORDING in C++
一.OPERATORS
除了基本的加减乘除,还有箭头运算符 -> ;常用于内存地址的&运算符;左尖号运算符 < ,常用来输入到流里;还有new 和 delete 运算符,逗号运算符(comma),括号运算符(blanket)。都可以重载(overloading)。
1.1 What is overloading?
Simply operator overloading just giving a new meaning or adding parameters to a existing operator.
In a case of overloading you allow to define or change the behavior of operator in your programme, this a very very useful feature that isn’t support in language such as java.
And C++ gives us full control.
1.2 Add and Multiply action whitout operator overloading
#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 Multiply(const Vector2& other) const
{
return Vector2(x * other.x, y * other.y);
}
};
int main()
{
Vector2 position(4.0f, 4.0f);
Vector2 speed(0.5f, 1.5f);
Vector2 powerup(1.1f, 1.1f);
Vector2 result = position.Add(speed);
Vector2 result = position.Add(speed.Multiply(powerup));
std::cin.get();
}
Vector2 result = position.Add(speed.Multiply(powerup));
It seems be annoying cause we just need a result that a position + speed * power;
But if we just write the code like this:
Vector2 result = position + speed * powerup;
This code doesn’t compile.
1.3 Overloading the + and * operators!
You can be overloading a + operator after the Add function like this:
Vector2 operator+(const Vector2& other)const
{
return Add(other);
}
or
Vector2 Add(const Vector2& other) const
{
return *this + other;
}
Vector2 operator+(const Vector2& other)const
{
return Vector2(x + other.x, y + other.y);
}
The same to Multiply:
Vector2 operator*(const Vector2& other) const
{
return Multiply(other);
}
So that the code can be complie!
Vector2 result = position + speed * powerup;
1.4 Overloading the << operator (shift left operator) and ==,!= operator.
And next we want to print the result, so we need to overloading the << operator which take in an output stream:
std::ostream& operator<<(std::ostream& stream, const Vector2& other)
{
stream << other.x << "," << other.y;
return stream;
}
std::cout << result << std::endl;
Overloading == and != to compare with other Vector2
bool operator==(const Vector2& other) const
{
return x == other.x && y == other.y;
}
bool operator!=(const Vector2& other) const
{
return !(*this == other);
}
if (result1 == result2)//if (result1 != result2)
{
//action
}
1.5 The operators can’t be overloading:
. (成员访问运算符)
.* (成员指针访问运算符)
∷(域运算符)
sizeof(长度运算符)
?: (条件运算符)
本文详细介绍了C++中的运算符重载,包括加法、乘法、左移位运算符及等于和不等于运算符的重载。通过示例展示了如何为自定义类型如`Vector2`重载这些运算符,使得代码更加简洁易读。同时,还涵盖了如何重载`<<`运算符以实现输出流的功能,并提供了比较运算符的重载方法。
4814

被折叠的 条评论
为什么被折叠?



