为复数重载+、-运算符,编程实现(6+7i)+(7+8i)和(6+7i)-(7+8i)的运算。
时间: 2023-09-05 22:08:09 浏览: 214
好的,这里是C++的实现:
```c++
#include<iostream>
using namespace std;
class Complex {
public:
Complex(double r = 0.0, double i = 0.0) :real(r), imag(i) {}
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}
private:
double real;
double imag;
};
int main() {
Complex c1(6, 7);
Complex c2(7, 8);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
cout << c3 << endl;
cout << c4 << endl;
return 0;
}
```
输出结果为:
```
13+15i
-1-1i
```
这里定义了一个名为Complex的类,用来表示复数。在类中重载了+和-运算符,以支持复数相加和相减的操作。同时,也重载了输出运算符<<,方便输出结果。在主函数中,分别创建了两个Complex对象c1和c2,表示两个复数。然后使用重载的+和-运算符完成了复数的加减运算,并将结果输出。
阅读全文