#ifndef__COMPLEX__ // 防卫式声明 guard; 名称自定义#define__COMPLEX__// 0. forward declarationsclasscomplex;
complex&__doapl(complex* ths,const complex& r);// 1. class declarationsclasscomplex// class head{public:// access level// constructor (ctor): the name same with the class name; automatically called;// ctor without return typecomplex(double r =0,double i =0)// default argument:re(r),im(i)// initialization list 初始化要早于{}内赋值{}// no return; {}内还可做其他事情,此处无需;// operator overloading of member function (has this pointer)
complex&operator+=(const complex&);// const member functiondoublereal()const{return re;}// inline funcdoubleimag()const{return im;}private:// visible within classdouble re, im;// datafriend complex&__doapl(complex*,const complex&);};// 2. class definition// 2.1 member function// 任何一个member func都有一个隐藏的this pointer, 指向调用者// 返回值是complex&是考虑到连续使用+=inline complex& complex::operator+=(const complex& r)// param this hidden here{return__doapl(this, r);}// 2.2 global functioninlinedoublereal(const complex& x){return x.real();}inlinedoubleimag(const complex& x){return x.imag();}// operator overloading of non member function, 因为复数不仅仅只能够加复数 ,所以设置为global func而非member func// return by value, becase the return is a local object (typename () is a temp object 临时对象, e.g., complex (...))inline complex operator+(const complex& x,const complex& y){returncomplex(real(x)+real(y),imag(x)+imag(y));}inline complex operator+(const complex& x,double y)// c + 5{returncomplex(real(x)+ y,imag(x));}inline complex operator+(double x,const complex& y)// 5 + c{returncomplex(x +real(y),imag(y));}inline complex operator+(const complex& x)// 正号{return x;}inline complex operator-(const complex& x){returncomplex(-real(x),-imag(x));}inlinebooloperator==(const complex& x,const complex& y){returnreal(x)==real(y)&&imag(x)==imag(y);}inlinebooloperator==(const complex& x,double y){returnreal(x)== y &&imag(x)==0;}inlinebooloperator==(double x,const complex& y){returnreal(y)==0&&imag(y)== x;}inlinebooloperator!=(const complex& x,const complex& y){returnreal(x)!=real(y)||imag(x)!=imag(y);}// ...inline complex conj(const complex& x)// 共轭{returncomplex(real(x),-imag(x));}// << 会将右边的东西作用到左边身上,比如作用到cout(标准输出流), 但cout又不 认识complex// << 不能写成member func,只能写作global func,其他操作符都可以// 若写作member func,那么左操作数必须是类的对象,然而<< 左边一般是cout...#include<iostream>// os不能是const,因为在往cout丢东西的时候,其实都在改变它的状态,所以得允 许修改// cout的返回值仍然是ostream,所以我们设计的时候返回值是ostream,然后os又不是local的,so by reference.
std::ostream&operator<<(std::ostream& os,const complex& x)// param os can be 'cout', which is a obj, and the typename is ostream{return os <<"("<<real(x)<<","<<imag(x)<<")";}// __doapl返回指针指向的object,是传递者// 而complex&是接收者,可以是object,也可以是reference// 传递者是无需知道接收者以什么形式接受(value or reference)// __doapl是friend,所以可以直接访问private中的datainline complex&__doapl(complex* ths,const complex& r){
ths->re += r.re;
ths->im += r.im;return*ths;}#endif