在 C++ 中,运算符重载是一种允许你自定义操作符行为的特性
operator=)、下标(operator[])和调用(operator())等运算符,你应该使用成员函数形式。而对于其他运算符,如加法(operator+)、乘法(operator*)等,你可以使用成员函数形式或非成员函数形式。const 关键字:当你的运算符不会修改对象状态时,请使用 const 关键字修饰成员函数。这样可以提高代码的安全性和可读性。operator<< 和 operator>>),通常将它们重载为非成员函数,并将 std::ostream 或 std::istream 作为第一个参数。以下是一个简单的示例,展示了如何在 C++ 中实现运算符重载:
#include<iostream>
class Complex {
public:
Complex(double real, double imag) : real_(real), imag_(imag) {}
// 重载加法运算符
Complex operator+(const Complex& other) const {
return Complex(real_ + other.real_, imag_ + other.imag_);
}
private:
double real_;
double imag_;
};
int main() {
Complex a(1, 2);
Complex b(3, 4);
Complex c = a + b;
std::cout << "Result: (" << c.real_ << ", " << c.imag_ << ")\n";
return 0;
}
在这个示例中,我们为 Complex 类重载了加法运算符,使得我们可以直接使用 + 运算符将两个 Complex 对象相加。