#ifndef _COMPLEX_
#define _COMPLEX_
using namespace std;
class complex {
public:
complex(double r,double i)
:re(r),im(i) //赋予初始值操作
{}
double getreal()const
{
return re;
}
double getimage()const
{
return im;
}
//重载+=符号
complex& operator +=(const complex&);
private:
double re, im; //实部与虚部
friend complex& _doapl(complex *,const complex& );
};
#endif // !_COMPLEX_
#include"Complex.h"
#include<iostream>
//重载+=号
inline complex&
complex::operator +=(const complex& r)
{
return _doapl(this, r);
}
complex&
_doapl(complex* ths, const complex& r)
{
ths->im += r.im; //实现具体的实部、虚部的相加 ths代表左边(本体)的数值
ths->re += r.re;
return *ths; //最终返回的是左边的本体 (引用类型)
}
//重载+号 他是非成员函数 不用在类内定义,因为类型不只有类中的数据类型
//返回值是一个具体的数而不是引用类型
complex operator +(const complex& x, const complex& y) //两个complex类型的相加
{
return complex(x.getreal()+y.getreal(),y.getimage()+x.getimage());
}
complex operator +(double x, const complex& y) //double型加上complex类型
{
return complex(x + y.getreal(), y.getimage());
}
//返回的类型是左边的那种类型 输出流
ostream &operator <<(ostream& os, const complex& r)
{
return os << "(" << r.getreal() << "," << r.getimage() << ")";
}
int main()
{
complex a1(5,8);
complex a2(a1);
a2 += a1;
cout << a2;
}