【问题描述】定义一个复数类,使得下面的代码能够工作: Complex c1(3,5); Complex c2=4.5; c1.add(c2); c1.show(); 【输入形式】无 【输出形式】 c1=3 + 5i c2=4.5 + 0i c1+c2=7.5 + 5i
时间: 2023-12-16 10:06:31 浏览: 140
以下是复数类的实现代码:
```cpp
#include <iostream>
using namespace std;
class Complex {
private:
double real; // 实部
double imag; // 虚部
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
void add(const Complex& c) {
real += c.real;
imag += c.imag;
}
void show() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 5);
Complex c2 = 4.5;
c1.add(c2);
cout << "c1=";
c1.show();
cout << "c2=";
c2.show();
cout << "c1+c2=";
(c1 + c2).show();
return 0;
}
```
输出结果为:
```
c1=7.5 + 5i
c2=4.5 + 0i
c1+c2=12 + 5i
```
阅读全文