编写一个复数类的例子,重载 +、 - 、= 运算符,进而实现复数加、减、赋值运算;c++完整代码
时间: 2023-06-12 19:04:50 浏览: 95
复数类和运算符重载 C++语言
4星 · 用户满意度95%
下面是一个简单的复数类实现,包括重载加、减、赋值运算符:
```c++
#include <iostream>
class Complex {
public:
Complex(double real = 0.0, double imag = 0.0) : m_real(real), m_imag(imag) {}
~Complex() {}
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) {
if (this != &rhs) {
m_real = rhs.m_real;
m_imag = rhs.m_imag;
}
return *this;
}
friend std::ostream& operator<<(std::ostream &os, const Complex &c);
private:
double m_real;
double m_imag;
};
std::ostream& operator<<(std::ostream &os, const Complex &c) {
os << "(" << c.m_real << ", " << c.m_imag << "i)";
return os;
}
int main() {
Complex a(1.0, 2.0);
Complex b(3.0, 4.0);
Complex c = a + b;
std::cout << a << " + " << b << " = " << c << std::endl;
c = a - b;
std::cout << a << " - " << b << " = " << c << std::endl;
a = b;
std::cout << "a = " << a << std::endl;
return 0;
}
```
输出结果为:
```
(1, 2i) + (3, 4i) = (4, 6i)
(1, 2i) - (3, 4i) = (-2, -2i)
a = (3, 4i)
```
可以看到,重载的复数加、减、赋值运算符都可以正常工作。
阅读全文