定义一个复数类complex类,包含数据成员实部和虚部。试编程实现复数的加法和减法
时间: 2024-03-22 14:37:08 浏览: 61
下面是一个简单的C++实现:
```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+(Complex const& obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
//复数减法
Complex operator-(Complex const& obj) {
Complex res;
res.real = real - obj.real;
res.imag = imag - obj.imag;
return res;
}
//输出复数
void print() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(1, 2), c2(3, 4);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
cout << "c1 = ";
c1.print();
cout << "c2 = ";
c2.print();
cout << "c1 + c2 = ";
c3.print();
cout << "c1 - c2 = ";
c4.print();
return 0;
}
```
输出结果为:
```
c1 = 1 + 2i
c2 = 3 + 4i
c1 + c2 = 4 + 6i
c1 - c2 = -2 - 2i
```