一、头文件
#ifndef __COMPLEX__
#define __COMPLEX__ //防卫式声明
/****************前置声明**************/
class complex;
complex&
_doapl(complex* ths, const complex& r);
/****************类的声明**************/
class complex
{
public:
complex(double r = 0, double i = 0): re(r), im(i){ }
complex& operator +=(const complex&);
double real() const { return re; }
double imag() const { return im; }
private:
double re, im;
friend complex& _doapl(complex*, const complex&);
};
/****************类的定义**************/
inline complex&
_doapl(complex* ths,complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
inline complex&
complex::operator += (const complex& r)
{
return _doapl(this,r);
}
inline complex
operator + (const complex& x, const complex& y)
{
return complex( real(x) + real(y), imag(x) + imag(y));
}
inline complex
operator + (const complex& x,const double& y)
{
return complex(x.real() + y, x.imag());
}
inline complex
operator + (const double&x, const complex& y)
{
return complex( x + y.real(), y.imag());
}
inline complex&
operator - (complex& x)
{
return complex(real(x), -imag(x));
}
inline complex&
operator + (complex& x)
{
return x;
}
#include<iostream>
ostream&
operator << (ostream& os, const complex& x)
{
return os << '(' << x.real() << ',' << x.imag() << ')';
}
#endif
二、源文件
#include "complex.h"
#include<iostream>
using namespace std;
int main(){
complex c1(1, 2);
complex c2(3, 4);
cout << c1 << endl;
cout << c2 << endl;
cout << "c1+c2=" << c1+c2 << endl;
cout << "c1+=c2" << c1+=c2 << endl;
cout << "-c1" << -c1 << endl;
cout << "+c2" << +c2 << endl;
cout << "5+c1" << 5+c1 << endl;
return 0;
}