c++为复数重载+、-运算符,编程实现(6+7i)+(7+8i)和(6+7i)-(7+8i)的运算。
时间: 2023-08-03 12:05:26 浏览: 52
好的,下面是C++代码实现:
```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; // 重载加法运算符
Complex operator-(const Complex& c) const; // 重载减法运算符
void display() const; // 显示复数
};
Complex Complex::operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex Complex::operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
void Complex::display() const {
cout << "(" << real << "+" << imag << "i)" << endl;
}
int main() {
Complex c1(6, 7), c2(7, 8), c3, c4;
c3 = c1 + c2;
c4 = c1 - c2;
cout << "c1 + c2 = ";
c3.display();
cout << "c1 - c2 = ";
c4.display();
return 0;
}
```
输出结果如下:
```
c1 + c2 = (13+15i)
c1 - c2 = (-1-1i)
```
以上代码中,我们定义了一个`Complex`类,并重载了加法和减法运算符。在`main`函数中,我们分别定义了两个复数对象`c1`和`c2`,然后使用重载的运算符对它们进行加减运算,最后输出结果。
相关推荐
![](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)