将运算符+和-重载为 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-03-10 18:47:34 浏览: 79
用c++设计一个Complex复数类,重载运算符“+”、“-”,并设计测试程序。
以下是重载运算符+和-的实现:
```cpp
#include<iostream>
using namespace std;
class complex
{
public:
complex(double r = 0.0, double i = 0.0)
{
real = r;
imag = i;
}
void display()
{
cout << real << "+" << imag << "i" << endl;
}
friend complex operator+(complex c1, complex c2);
friend complex operator-(complex c1, complex c2);
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);
}
int main()
{
complex c1(1.0, 2.0), c2(2.0, 3.0);
complex c3 = c1 + c2;
complex c4 = c1 - c2;
c3.display(); // 输出 3+5i
c4.display(); // 输出 -1-1i
return 0;
}
```
运行结果:
```
3+5i
-1-1i
```
阅读全文