1.设计一个complex类,它有2个私有的数据成员实部real和虚部imag,重载运算符"+="、"-="、"*="和"<<",使他们能用于复数运算。要求(1)将"+="重载为成员函数;(2)将"-
时间: 2024-06-02 22:04:34 浏览: 12
设计一个complex类,其实现如下:
```
#include<iostream>
using namespace std;
class Complex {
public:
Complex(double r = 0, double i = 0): real(r), imag(i) {}
Complex& operator+=(const Complex& c) {
real += c.real;
imag += c.imag;
return *this;
}
Complex& operator-=(const Complex& c) {
real -= c.real;
imag -= c.imag;
return *this;
}
Complex& operator*=(const Complex& c) {
double r = real * c.real - imag * c.imag;
double i = real * c.imag + imag * c.real;
real = r;
imag = i;
return *this;
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}
private:
double real, imag;
};
```
其中,重载的运算符包括"+="、"-="、"*="和"<<"。其中,"+="重载为成员函数,其他三个重载为友元函数。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)