下面是一个示例,演示了如何在C++中重载运算符:
#include <iostream>
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// 重载加法运算符
Complex operator+(const Complex& other) {
Complex result;
result.real = this->real + other.real;
result.imag = this->imag + other.imag;
return result;
}
// 重载输出运算符
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real << " + " << c.imag << "i";
return os;
}
};
int main() {
Complex c1(2.5, 3.7);
Complex c2(1.8, 2.4);
Complex sum = c1 + c2;
std::cout << "Sum: " << sum << std::endl;
return 0;
}
在上面的示例中,我们定义了一个名为Complex
的类,表示复数。我们重载了加法运算符+
,使得两个Complex
对象可以相加。我们还重载了输出运算符<<
,以便能够直接输出Complex
对象。
在main
函数中,我们创建了两个Complex
对象c1
和c2
,然后使用重载的加法运算符将它们相加,并将结果赋给sum
。最后,我们使用重载的输出运算符将sum
输出到标准输出流。
输出结果为:
Sum: 4.3 + 6.1i
通过运算符重载,我们可以为自定义类型定义特定的运算行为,使其更符合我们的需求。