C++定义一个复数类 complex ,重载运算符'+'、'-'、'*',使之能用于复数的加、减、乘,运算符重载函数作为 complex 类的成员函数。编写程序,分别求两个复数的和、差、积。
时间: 2024-03-12 10:50:00 浏览: 119
用c++设计一个Complex复数类,重载运算符“+”、“-”,并设计测试程序。
好的,下面是 C++ 的代码实现:
```c++
#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);
}
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, real*c.imag+imag*c.real);
}
void display() const {
cout << "(" << real << ", " << imag << "i)" << endl;
}
};
int main() {
complex c1(1, 2);
complex c2(3, 4);
complex sum = c1 + c2;
complex diff = c1 - c2;
complex prod = c1 * c2;
cout << "c1 = ";
c1.display();
cout << "c2 = ";
c2.display();
cout << "c1 + c2 = ";
sum.display();
cout << "c1 - c2 = ";
diff.display();
cout << "c1 * c2 = ";
prod.display();
return 0;
}
```
输出结果为:
```
c1 = (1, 2i)
c2 = (3, 4i)
c1 + c2 = (4, 6i)
c1 - c2 = (-2, -2i)
c1 * c2 = (-5, 10i)
```
其中,`complex` 类的成员函数 `operator+`、`operator-` 和 `operator*` 分别重载了加、减、乘运算符。在 `main` 函数中,我们创建了两个复数对象 `c1` 和 `c2`,并对它们进行加、减、乘操作,将结果存储在 `sum`、`diff` 和 `prod` 中,最后输出结果。
阅读全文