编写一个复数类的例子,重载 +、 - 、= 运算符,进而实现复数加、减、赋值运算;
时间: 2023-06-12 12:04:00 浏览: 69
以下是一个实现复数类的例子,包括重载 + 、- 、= 运算符,实现复数加、减、赋值运算。
```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) {
real = c.real;
imag = c.imag;
return *this;
}
// 打印复数
void print() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
// 创建两个复数对象
Complex c1(1, 2);
Complex c2(3, 4);
// 复数加法
Complex c3 = c1 + c2;
cout << "c1 + c2 = ";
c3.print();
// 复数减法
Complex c4 = c1 - c2;
cout << "c1 - c2 = ";
c4.print();
// 复数赋值
c1 = c2;
cout << "c1 = ";
c1.print();
return 0;
}
```
输出结果:
```
c1 + c2 = 4 + 6i
c1 - c2 = -2 - 2i
c1 = 3 + 4i
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)