用运算符重载设计复数类,实现复数的+、-、*、/运算
时间: 2024-01-30 15:02:47 浏览: 91
用重载运算符的方法进行复数的加、减、乘、除运算
以下是一个使用运算符重载设计的复数类,实现了+、-、*、/运算:
```cpp
#include <iostream>
using namespace std;
class Complex {
public:
// 构造函数
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 运算符重载
Complex operator+(const Complex& c2) const {
return Complex(real + c2.real, imag + c2.imag);
}
Complex operator-(const Complex& c2) const {
return Complex(real - c2.real, imag - c2.imag);
}
Complex operator*(const Complex& c2) const {
return Complex(real * c2.real - imag * c2.imag, real * c2.imag + imag * c2.real);
}
Complex operator/(const Complex& c2) const {
double denominator = c2.real * c2.real + c2.imag * c2.imag;
return Complex((real * c2.real + imag * c2.imag) / denominator, (imag * c2.real - real * c2.imag) / denominator);
}
// 输出运算符重载
friend ostream& operator<<(ostream& os, const Complex& c) {
os << "(" << c.real << ", " << c.imag << "i)";
return os;
}
private:
double real, imag; // 实部和虚部
};
int main() {
Complex c1(1, 2), c2(2, 3);
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
// 加法运算
Complex c3 = c1 + c2;
cout << "c1 + c2 = " << c3 << endl;
// 减法运算
Complex c4 = c1 - c2;
cout << "c1 - c2 = " << c4 << endl;
// 乘法运算
Complex c5 = c1 * c2;
cout << "c1 * c2 = " << c5 << endl;
// 除法运算
Complex c6 = c1 / c2;
cout << "c1 / c2 = " << c6 << endl;
return 0;
}
```
输出结果:
```
c1 = (1, 2i)
c2 = (2, 3i)
c1 + c2 = (3, 5i)
c1 - c2 = (-1, -1i)
c1 * c2 = (-4, 7i)
c1 / c2 = (0.615385, -0.0769231i)
```
阅读全文