声明一个复数类 Complex,重载运算符“+”,“-”,“*”,“/”,使之能用于复数的加、减、乘、除,运算符重载函数作为 Complex类的成员函数。编程序,分别求两个复数之和、差、积和商。
时间: 2023-06-17 11:08:33 浏览: 66
定义复数类Complex,进行运算符重载
5星 · 资源好评率100%
以下是一个简单的实现:
```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);
}
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);
}
Complex operator/(const Complex& c) const {
double denominator = c.real * c.real + c.imag * c.imag;
return Complex((real * c.real + imag * c.imag) / denominator, (imag * c.real - real * c.imag) / denominator);
}
friend ostream& operator<<(ostream& out, const Complex& c);
};
ostream& operator<<(ostream& out, const Complex& c) {
out << c.real << " + " << c.imag << "i";
return out;
}
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
cout << "c1 + c2 = " << c1 + c2 << endl;
cout << "c1 - c2 = " << c1 - c2 << endl;
cout << "c1 * c2 = " << c1 * c2 << endl;
cout << "c1 / c2 = " << c1 / c2 << endl;
return 0;
}
```
输出结果:
```
c1 = 1 + 2i
c2 = 3 + 4i
c1 + c2 = 4 + 6i
c1 - c2 = -2 - 2i
c1 * c2 = -5 + 10i
c1 / c2 = 0.44 - 0.08i
```
阅读全文