本文共 1285 字,大约阅读时间需要 4 分钟。
#includeusing namespace std;#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;} // 类成员函数不改变输入参数则尽量使用const double imag() const { return im;} //二元运算符用成员重载时, 只需要一个参数,另一个参数由this指针传入 complex operator + (const complex& y){ return complex(this->real()+y.re, this->imag()+y.im); } private: double re, im; friend complex& __doapl (complex*, const complex&); // 友元函数};inline complex& complex::operator += (const complex& r){ //内联函数 return __doapl (this, r);}inline complex& __doapl (complex*ths, const complex& r){ // 友元函数类外定义 ths->re += r.re; ths->im += r.im; return *ths;}ostream& operator << (ostream& os, const complex& x){ return os << '(' << x.real() << ',' << x.imag() << ')' ; }#endifint main(){ complex c1(2,3); complex c2(1,1); complex c3; c1 += c2; c3 = c1 + c2; cout << c1.real() << endl; cout << c1.imag() << endl; cout << c3 << endl; return 0;}
34(4,5)
转载地址:http://umwrf.baihongyu.com/