C++ 中的运算符重载允许为用户自定义类型(类或结构体)赋予运算符特定功能,使其操作更直观。以下是运算符重载的关键点:
1. 基本语法
-
成员函数重载:运算符作为类的成员函数,左操作数为当前对象 (
this
),右操作数为参数。class Complex { public:Complex operator+(const Complex& other) const {return Complex(real + other.real, imag + other.imag);} private:double real, imag; };
-
全局函数重载:需声明为友元(若访问私有成员),参数为左右操作数。
class Complex {friend Complex operator+(const Complex& a, const Complex& b); };Complex operator+(const Complex& a, const Complex& b) {return Complex(a.real + b.real, a.imag + b.imag)