

新闻资讯
技术学院运算符重载允许自定义类型使用内置运算符;成员函数适用于左操作数为本类对象(如+、==、[]、=、->、()),非成员函数(常为友元)支持对称操作(如int+obj)和流操作(
运算符重载是 C++ 中让自定义类型像内置类型一样使用 +、==、[]、
大部分运算符都可重载,包括算术(+ - * / %)、关系(== != =)、逻辑(&& || !)、赋值(= += -=)、下标([])、函数调用(())、指针访问(->)、输入输出(>)、new/delete 等。
选择成员函数还是非成员函数,主要看左操作数是否必须是当前类对象:
假设有一个简单的 Vector2 类:
class Vector2 {
public:
float x, y;
Vector2(float x = 0, float y = 0) : x(x), y(y) {}
// 成员版:+(左操作数是 Vector2)
Vector2 operator+(const Vector2& other) const {
return Vector2(x + other.x, y + other.y);
}
// 成员版:+=(修改自身,返回引用)
Vector2& operator+=(const Vector2& other) {
x += other.x; y += other.y;
return *this;
}
// 成员版:==(常量成员,不修改对象)
bool operator==(const Vector2& other) const {
return x == other.x && y == other.y;
}
// 成员版:[](非常量和常量两个版本)
float& operator[](int i) {
return (i == 0) ? x : y;
}
const float& operator[](int i) const {
return (i == 0) ? x : y;
}};
// 非成员版:stream)
std::ostream& operator
// 非成员版:+ 支持 int + Vector2(需友元或 public 成员)
Vector2 operator+(float s, const Vector2& v) {
return Vector2(s + v.x, s + v.y);
}
必须注意的细节和陷阱
写错容易引发隐式转换、效率问题或语义混乱:
它们必须是非成员函数,因为左操作数是 std::istream 或 std::ostream,你无法给标准库类添加成员函数。同时,通常需要访问类的私有成员,所以常声明为 friend:
class Vector2 {
float x, y;
public:
friend std::ostream& operator<<(std::ostream& os, const Vector2& v);
friend std::istream& operator>>(std::istream& is, Vector2& v);
};
std::ostream& operator<<(std::ostream& os, const Vector2& v) {
os << v.x << " " << v.y; // 直接访问私有成员
return os;
}
std::istream& operator>>(std::istream& is, Vector2& v) {
is >> v.x >> v.y;
return is;
}