将运算符+和-重载为 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; //复数虚部 }; 完成该类的实现并编译运行该程序。
时间: 2024-01-12 22:04:13 浏览: 66
Complex复数类
以下是重载运算符+和-的 complex 类的实现代码:
```
#include<iostream>
class complex
{
public:
complex(double r = 0.0, double i = 0.0)
{
real = r;
imag = i;
}
complex operator+(complex c2)
{
return complex(real + c2.real, imag + c2.imag);
}
complex operator-(complex c2)
{
return complex(real - c2.real, imag - c2.imag);
}
void display()
{
std::cout << "(" << real << ", " << imag << "i)" << std::endl;
}
private:
double real;
double imag;
};
int main()
{
complex c1(1.0, 2.0);
complex c2(3.0, 4.0);
complex c3 = c1 + c2;
c3.display();
complex c4 = c1 - c2;
c4.display();
return 0;
}
```
运行结果:
```
(4, 6i)
(-2, -2i)
```
阅读全文