c++定义复数类的加法与减法,使之能够执行下列运算: Complex a(2,5), b(7, 8), c(0, 0); c=a+b; c=4.1+a; c=b-5.6; 【输入形式】无 【输出形式】各复数运算结果 【样例输入】无 【样例输出】 9+i13 6.1+i5 1.4+i8
时间: 2024-03-22 19:42:14 浏览: 41
下面是一种实现复数类的方法:
```c++
#include <iostream>
using namespace std;
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
Complex operator+(double r) const {
return Complex(real + r, imag);
}
friend Complex operator+(double r, const Complex& c) {
return c + r;
}
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
Complex operator-(double r) const {
return Complex(real - r, imag);
}
friend Complex operator-(double r, const Complex& c) {
return Complex(r - c.real, -c.imag);
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real;
if (c.imag >= 0) os << "+";
os << c.imag << "i";
return os;
}
};
int main() {
Complex a(2, 5), b(7, 8), c(0, 0);
c = a + b;
cout << c << endl;
c = 4.1 + a;
cout << c << endl;
c = b - 5.6;
cout << c << endl;
return 0;
}
```
运行结果:
```
9+13i
6.1+5i
1.4+8i
```