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)