用运算符重载设计复数类,实现复数的+、-、*、/和<<运算。
时间: 2024-05-01 14:23:18 浏览: 45
好的,以下是复数类的实现代码:
```C++
#include <iostream>
using namespace std;
class Complex {
public:
Complex(double real = 0.0, double imag = 0.0) : m_real(real), m_imag(imag) {}
Complex operator+(const Complex& rhs) const {
return Complex(m_real + rhs.m_real, m_imag + rhs.m_imag);
}
Complex operator-(const Complex& rhs) const {
return Complex(m_real - rhs.m_real, m_imag - rhs.m_imag);
}
Complex operator*(const Complex& rhs) const {
double real = m_real * rhs.m_real - m_imag * rhs.m_imag;
double imag = m_real * rhs.m_imag + m_imag * rhs.m_real;
return Complex(real, imag);
}
Complex operator/(const Complex& rhs) const {
double denominator = rhs.m_real * rhs.m_real + rhs.m_imag * rhs.m_imag;
double real = (m_real * rhs.m_real + m_imag * rhs.m_imag) / denominator;
double imag = (m_imag * rhs.m_real - m_real * rhs.m_imag) / denominator;
return Complex(real, imag);
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.m_real << " + " << c.m_imag << "i";
return os;
}
private:
double m_real;
double m_imag;
};
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
```
阅读全文