为复数类增加重载运算符-、-=用友元函数
时间: 2024-03-14 12:43:28 浏览: 239
可以这样实现:
```c++
#include <iostream>
class Complex {
public:
Complex(double r = 0, double i = 0): real(r), imag(i) {}
// 定义友元函数
friend Complex operator-(const Complex& c1, const Complex& c2);
friend Complex operator-=(Complex& c1, const Complex& c2);
void display() const {
std::cout << real << " + " << imag << "i" << std::endl;
}
private:
double real;
double imag;
};
// 重载运算符-,返回一个新的复数类
Complex operator-(const Complex& c1, const Complex& c2) {
return Complex(c1.real - c2.real, c1.imag - c2.imag);
}
// 重载运算符-=,修改原有的复数类
Complex operator-=(Complex& c1, const Complex& c2) {
c1.real -= c2.real;
c1.imag -= c2.imag;
return c1;
}
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 - c2;
std::cout << "c3 = ";
c3.display(); // 输出:c3 = -2 + -2i
c1 -= c2;
std::cout << "c1 = ";
c1.display(); // 输出:c1 = -2 + -2i
return 0;
}
```
在上面的代码中,我们为 `Complex` 类增加了两个友元函数 `operator-` 和 `operator-=`,分别用于实现重载运算符 `-` 和 `-=`。`operator-` 重载运算符 `-`,返回一个新的 `Complex` 类,而 `operator-=` 重载运算符 `-=`,修改原有的 `Complex` 类。注意,在 `operator-=` 中,我们返回的是修改后的 `c1`,这样可以支持链式操作。
阅读全文
相关推荐














