OX01 首先还是把实现comples类的代码贴过来..
#ifndef __MYCOMPLEX__
#define __MYCOMPLEX__
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&);
};
include <iostream>
inline ostream&
operator << (ostream& os , const comples& r)
{
return os << "("<<real(r)<<","<<imag(r)<<")"<<endl;
}
inline complex&
__doapl (complex* ths, const complex& r)
{
ths->re += r.re; ths->im += r.im;
return *ths;
}
inline complex&
complex::operator += (const complex& r)
{
return __doapl (this, r);
}
inline double
imag (const complex& x){
return x.imag ();
}
inline double
real (const complex& x)
{
return x.real ();
}
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, double y)
{
return complex (real (x) + y, imag (x));
}
inline complex
operator + (double x, const complex& y)
{
return complex (x + real (y), imag (y));
}
inline complex
operator + (const complex& x)
{
return x;
}
inline complex
operator - (const complex& x)
{
return complex (-real (x), -imag (x));
}
inline bool
operator == (const complex& x, const complex& y)
{
return real (x) == real (y) && imag (x) == imag (y);
}
inline bool
operator == (const complex& x, double y)
{
return real (x) == y && imag (x) == 0;
}
#endif __MYCOMPLEX__
OX02 关键点
1.防卫式的声明
2.数据写在private里面
3.构造函数的初始化用:
4.const 是否使用分析 如果函数不改变数据加const ,蓝本不变(参数),加const
5.friend :函数要直接使用别人的数据,同一个类的对象互为friend
6.函数设计,接受是否用reference,传入是否用reference
7.成员函数隐藏的this~ 不能写在参数中,但是函数内可用
8.操作符重构,operator 关键字