C++运算符重载需遵循规则,不能重载如.、::等运算符,优先级不变;成员函数用于需访问私有成员或左操作数为类对象的情况,如赋值运算符;全局函数适用于支持隐式转换或左操作数非类对象的情况,如流输出运算符;返回类型应符合语义,算术运算返回新对象,赋值返回引用以支持链式操作。

C++运算符重载允许我们自定义运算符的行为,但必须遵循一些规则。选择成员函数还是全局函数实现重载,取决于运算符的特性和类的设计。
C++运算符重载,本质上是赋予运算符新的含义,让它们能作用于自定义类型。但并非所有运算符都能重载,例如
.
.*
::
sizeof
?:
运算符重载可以通过两种方式实现:成员函数和全局函数。选择哪种方式,需要根据具体情况判断。
当运算符需要访问类的私有成员,或者运算符左侧的操作数必须是该类的对象时,通常选择成员函数。例如,赋值运算符
=
[]
()
->
立即学习“C++免费学习笔记(深入)”;
考虑一个简单的
Vector2D
class Vector2D {
private:
    double x, y;
public:
    Vector2D(double x = 0, double y = 0) : x(x), y(y) {}
    // 使用成员函数重载加法运算符
    Vector2D operator+(const Vector2D& other) const {
        return Vector2D(x + other.x, y + other.y);
    }
    // 使用成员函数重载输出运算符(不推荐,更好的方式见下文)
    /*
    std::ostream& operator<<(std::ostream& os, const Vector2D& v) {
        os << "(" << v.x << ", " << v.y << ")";
        return os;
    }
    */
    double getX() const { return x; }
    double getY() const { return y; }
};在这里,
operator+
Vector2D
v1 + v2
v1.operator+(v2)
当运算符需要支持隐式类型转换,或者运算符左侧的操作数不是该类的对象时,通常选择全局函数。一个典型的例子是流插入运算符
<<
>>
继续上面的
Vector2D
std::cout << v1
operator<<
std::cout
Vector2D
std::ostream& operator<<(std::ostream& os, const Vector2D& v) {
    os << "(" << v.getX() << ", " << v.getY() << ")";
    return os;
}注意,为了访问
Vector2D
x
y
getX()
getY()
operator<<
Vector2D
class Vector2D {
private:
    double x, y;
public:
    Vector2D(double x = 0, double y = 0) : x(x), y(y) {}
    friend std::ostream& operator<<(std::ostream& os, const Vector2D& v);
    double getX() const { return x; }
    double getY() const { return y; }
};
std::ostream& operator<<(std::ostream& os, const Vector2D& v) {
    os << "(" << v.x << ", " << v.y << ")";
    return os;
}运算符重载的返回值类型应该与运算符的语义保持一致。例如,算术运算符(如
+
-
*
/
=
+=
-=
==
!=
<
>
bool
赋值运算符返回引用是为了支持链式赋值,例如
a = b = c
class MyInt {
private:
    int value;
public:
    MyInt(int value = 0) : value(value) {}
    MyInt& operator=(const MyInt& other) {
        value = other.value;
        return *this;
    }
    int getValue() const { return value; }
};
int main() {
    MyInt a(1), b(2), c(3);
    a = b = c; // 链式赋值
    std::cout << a.getValue() << std::endl; // 输出 3
    return 0;
}以上就是C++运算符重载规则 成员函数与全局函数的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号