将运算符+和-重载为 complex 类的成员函数。 #include<iostream.h> class complex //复数类声明 { public: //外部接口 complex(double r=0.0,double i=0.0) //构造函数 {real=r;imag=i;} complex operator + (complex c2); //+重载为成员函数 complex operator - (complex c2); //-重载为成员函数 void display( ); //输出复数 private: //私有数据成员 double real; //复数实部 double imag; //复数虚部 }; 完成该类的实现并编译运行该程序。 20
时间: 2023-11-29 12:04:54 浏览: 77
以下为重载后的代码:
```cpp
#include<iostream>
using namespace std;
class complex //复数类声明
{
public: //外部接口
complex(double r = 0.0, double i = 0.0) //构造函数
{
real = r;
imag = i;
}
complex operator+(complex c2) //+重载为成员函数
{
complex temp;
temp.real = real + c2.real;
temp.imag = imag + c2.imag;
return temp;
}
complex operator-(complex c2) //-重载为成员函数
{
complex temp;
temp.real = real - c2.real;
temp.imag = imag - c2.imag;
return temp;
}
void display() //输出复数
{
cout << "(" << real << "," << imag << ")" << endl;
}
private: //私有数据成员
double real; //复数实部
double imag; //复数虚部
};
int main()
{
complex c1(1, 2);
complex c2(3, 4);
complex c3 = c1 + c2;
complex c4 = c1 - c2;
c3.display();
c4.display();
return 0;
}
```
输出结果为:
```
(4,6)
(-2,-2)
```
阅读全文