侯捷老师的C++代码: 基于对象之一 无指针类型 复数类实现
//makefile cc = g++ prom = complex obj = complex.o $(prom):$(obj) rm -rf *.exe; $(cc) -o $(prom) $(obj)
//complex.h #ifndef __COMPLEX__ #define __COMPLEX__ class complex{ public: complex(double r = 0, double i = 0) :re(r) , im(i){} complex& operator+=(const complex&); double real() const {return re;} double ima() const {return im;} private: double re, im; friend complex& __doapl(complex* , const complex &); }; inline complex& __doapl(complex* ths, const complex& r) { ths->re += r.re; ths->im += r.im; return *ths; } inline complex& complex::operator +=(const complex& rhs) { return __doapl(this, rhs); } inline double real(const complex& r) { return r.real(); } inline double im(const complex& r) { return r.ima(); } inline complex operator +(const complex& l, const complex& r) { return complex(real(l) + real(r), im(l) + im(r)); } #include <iostream> using namespace std; ostream & operator << (ostream& os , const complex &r) { os << "(" << real(r) << "," << im(r) << ")"; } #endif
//complex.cpp #include "complex.h" int main() { complex c1; cout << c1 << endl; complex c2(1,3); cout << c2 << endl; c2+=c2; cout << c2 << endl; return 0; }