将运算符重载为complex类的友元函数的完整代码
时间: 2024-03-09 10:50:38 浏览: 75
下面是将运算符重载为complex类的友元函数的完整代码:
```cpp
#include <iostream>
using namespace std;
class complex {
public:
complex(double r = 0.0, double i = 0.0) : re(r), im(i) {}
friend complex operator+(const complex& a, const complex& b);
friend complex operator-(const complex& a, const complex& b);
friend complex operator*(const complex& a, const complex& b);
friend complex operator/(const complex& a, const complex& b);
friend ostream& operator<<(ostream& os, const complex& c);
private:
double re, im;
};
complex operator+(const complex& a, const complex& b)
{
return complex(a.re + b.re, a.im + b.im);
}
complex operator-(const complex& a, const complex& b)
{
return complex(a.re - b.re, a.im - b.im);
}
complex operator*(const complex& a, const complex& b)
{
return complex(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re);
}
complex operator/(const complex& a, const complex& b)
{
double r = b.re * b.re + b.im * b.im;
return complex((a.re * b.re + a.im * b.im) / r, (a.im * b.re - a.re * b.im) / r);
}
ostream& operator<<(ostream& os, const complex& c)
{
os << "(" << c.re << ", " << c.im << ")";
return os;
}
int main()
{
complex a(1.0, 2.0);
complex b(3.0, 4.0);
complex c = a + b;
complex d = a - b;
complex e = a * b;
complex f = a / b;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a + b = " << c << endl;
cout << "a - b = " << d << endl;
cout << "a * b = " << e << endl;
cout << "a / b = " << f << endl;
return 0;
}
```
在这个示例中,我们还定义了一个`operator<<`函数,用于将`complex`对象输出到标准输出流中。在`main`函数中,我们创建了两个`complex`对象`a`和`b`,然后使用重载的运算符来执行加、减、乘和除运算,并将结果输出到控制台。
阅读全文