3 + 5,因為 int 已經支援 +
+、== 等操作#include <iostream>
using namespace std;
class Vector2D
{
public:
int x, y;
Vector2D operator+(const Vector2D& other)
{
return Vector2D(x + other.x, y + other.y);
}
bool operator==(const Vector2D& other)
{
return (x == other.x && y == other.y);
}
};
int main()
{
Vector2D v1(2, 3), v2(4, 1);
Vector2D v3 = v1 + v2;
cout << "v3 = (" << v3.x << ", " << v3.y << ")" << endl;
if (v1 == v2)
{
cout << "v1 和 v2 相等" << endl;
}
else
{
cout << "v1 和 v2 不相等" << endl;
}
return 0;
}
.、?:、sizeof 不能。+、/(數學類別)==、!=、<(比較類別)[](像陣列存取)()(函式呼叫運算子)<<、>>(輸出輸入)運算子多載能讓自訂類別
像內建型別一樣方便使用
如複數、向量、矩陣等數學物件
用 +、- 就能進行運算
而不用自己寫一堆函式呼叫