(2) 将运算符+和-重载为 complex 类的友元函数。 #include<iostream.h> class complex { public: complex(double r=0.0,double i=0.0) { real=r; imag=i; } //构造函数 friend complex operator + (complex c1,complex c2); //重载运算符+为友元函数 friend complex operator - (complex c1,complex c2); //重载运算符-为友元函数 void display(); //显示复数的值 private: //私有成员 double real; double imag; }; 完成该类的实现并编译运行该程序。
时间: 2024-01-09 13:03:47 浏览: 74
完整实现代码如下:
```cpp
#include<iostream>
using namespace std;
class complex {
public:
complex(double r = 0.0, double i = 0.0) {
real = r;
imag = i;
} //构造函数
friend complex operator+(complex c1, complex c2); //重载运算符+为友元函数
friend complex operator-(complex c1, complex c2); //重载运算符-为友元函数
void display(); //显示复数的值
private: //私有成员
double real;
double imag;
};
complex operator+(complex c1, complex c2) {
return complex(c1.real + c2.real, c1.imag + c2.imag);
}
complex operator-(complex c1, complex c2) {
return complex(c1.real - c2.real, c1.imag - c2.imag);
}
void complex::display() {
cout << "(" << real << ", " << imag << "i)" << endl;
}
int main() {
complex c1(1, 2);
complex c2(3, 4);
complex c3 = c1 + c2;
complex c4 = c1 - c2;
c1.display();
c2.display();
c3.display();
c4.display();
return 0;
}
```
运行结果:
```
(1, 2i)
(3, 4i)
(4, 6i)
(-2, -2i)
```
可以看到,重载后的运算符+和- 可以直接对两个复数对象进行运算,且结果正确。
阅读全文