复数类
#pragma once
#ifndef __COMPLEX__
#define __COMPLEX__
#include<iostream>
using namespace std;
class my_complex
{
private:
double re, im;
friend my_complex& __doapl(my_complex*, const my_complex &);
public:
my_complex(double r = 0, double i = 0) :
re(r), im(i)
{};
my_complex& operator+= (const my_complex&);
double real() const { return re; }
double imag() const { return im; }
};
inline my_complex&
__doapl(my_complex* ths, const my_complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
inline my_complex&
my_complex::operator += (const my_complex& r)
{
return __doapl(this, r);
}
inline double
real(const my_complex& x)
{
return x.real();
}
inline double
imag(const my_complex &x)
{
return x.imag();
}
inline my_complex
operator + (const my_complex& x, const my_complex& y)
{
return my_complex(real(x) + real(y),
imag(x) + imag(y));
}
inline my_complex
operator + (const my_complex& x, double y)
{
return my_complex(real(x) + y, imag(x));
}
inline my_complex
operator + (double x, const my_complex& y)
{
return my_complex(x + real(y), imag(y));
}
inline my_complex
operator + (const my_complex& x)
{
return x;
}
inline my_complex
operator - (const my_complex& x)
{
return my_complex(-real(x), -imag(x));
}
ostream& operator<< (ostream& os, const my_complex& x)
{
return os << '(' << real(x) << ','
<< imag(x) << ')';
}
inline bool
operator == (const my_complex& x, const my_complex& y)
{
return real(x) == real(y) && imag(x) == imag(y);
}
inline bool
operator == (const my_complex& x, double y)
{
return real(x) == y && imag(x) == 0;
}
inline bool
operator == (double x, const my_complex& y)
{
return real(y) == x && imag(y) == 0;
}
inline my_complex
conj(const my_complex& x)
{
return my_complex(x.real(), -x.imag());
}
#endif
测试主程序
#include "Mycomplex.h"
int main()
{
my_complex c1(2, 1);
my_complex c2;
cout << c1 << endl;
cout << c2 << endl;
c2 = c1 + 5;
c2 = 7 + c1;
c2 = c1 + c2;
c2 += c1;
c2 += 3;
cout << (c1 == c2) << endl;
cout << conj(c1) << endl;
return 0;
}