阅读量:99
在C++中,运算符重载是一种允许你自定义已有运算符行为的方法
#include
using namespace std;
class Complex {
public:
Complex(double real = 0, double imag = 0) : real_(real), imag_(imag) {}
// 重载加法运算符
Complex operator+(const Complex& other) const {
return Complex(real_ + other.real_, imag_ + other.imag_);
}
// 重载输出运算符
friend ostream& operator<<(ostream& os, const Complex& c) {
os << "(" << c class="hljs-string">", " << c class="hljs-string">")";
return os;
}
private:
double real_;
double imag_;
};
int main() {
Complex c1(3, 4);
Complex c2(1, 2);
Complex c3 = c1 + c2;
cout << "c1 + c2 = " << c3 class="hljs-keyword">return 0;
}
在这个例子中,我们定义了一个名为Complex的类,它表示复数。我们重载了加法运算符(operator+)以允许两个复数相加。同时,我们还重载了输出运算符(operator<<),以便在输出复数时提供更友好的格式。
在main函数中,我们创建了两个复数对象c1和c2,并将它们相加得到一个新的复数对象c3。然后我们使用重载的输出运算符将c3打印出来。