定义一个复数类complex ,重载运算符"<<"实现复数形式的输出,重载运算符“+”使之用于复数的加法运算,两个复数之和,复数与整数之和
时间: 2024-01-22 09:17:20 浏览: 134
定义复数类Complex,进行运算符重载
5星 · 资源好评率100%
下面是一个示例代码:
```c++
#include <iostream>
using namespace std;
class complex {
private:
double real, imag; // 复数的实部和虚部
public:
complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
friend ostream& operator<<(ostream& os, const complex& c);
friend complex operator+(const complex& c1, const complex& c2);
friend complex operator+(const complex& c, const int& i);
};
ostream& operator<<(ostream& os, const complex& c) {
os << c.real;
if (c.imag > 0) os << "+";
if (c.imag != 0) os << c.imag << "i";
return os;
}
complex operator+(const complex& c1, const complex& c2) {
return complex(c1.real + c2.real, c1.imag + c2.imag);
}
complex operator+(const complex& c, const int& i) {
return complex(c.real + i, c.imag);
}
int main() {
complex c1(1.0, 2.0), c2(3.0, -4.0), c3;
c3 = c1 + c2;
cout << c1 << " + " << c2 << " = " << c3 << endl;
c3 = c1 + 5;
cout << c1 << " + " << 5 << " = " << c3 << endl;
return 0;
}
```
输出结果为:
```
1+2i + 3-4i = 4-2i
1+2i + 5 = 6+2i
```
这里使用了友元函数来重载输出运算符和加法运算符。在输出时,如果虚部为负数,则会自动输出符号。在加法运算时,复数对象与整数相加时,整数被视为虚部为0的复数。
阅读全文