例8-1:加运算符+ class comp1ex//复数类声明 public: /构造函数 complex(double r=0.o, double i=0.0) real=ri imag=ii 1 complex operator t (complex c2)i //+重载为成员函数 void display o)i private: double reali double imagi
例8-1:加运算符 + class complex //复数类声明 { public: //构造函数 complex(double r=0.0,double i=0.0) { real=r; imag=i; } complex operator + (complex c2); //+重载为成员函数 void display(); private: double real; double imag; };
例8-1:运算符+ complexcomplex:: operator (+(complex c2) /重载运算符+的实现 I complex ci 对运算符+进行重载 c. real c2 real real c imag c2 imag t imag; return complex(c real,c imag)i int main o //主函数 调用重载函数+ complex cl(5, 4) c3=c1+c2; //使用重载运算符完成复数加法 cout<<"c3=c1+c2="; c3display o
例8-1:运算符 + complex complex::operator + (complex c2) //重载运算符 + 的实现 { complex c; c.real = c2.real + real; c.imag = c2.imag + imag; return complex(c.real,c.imag); } 对运算符+进行重载 int main() //主函数 { complex c1(5,4),c2(2,10),c3; c3 = c1 + c2; //使用重载运算符完成复数加法 cout << "c3=c1+c2="; c3.display(); } 调用重载函数 +
可以被重载的运算符(双目 算术运算 +(加),-(减),*(乘),/(除),%(取余) 位运算 <<(左移),>>(右移),丨(或),&(与),(异或) 赋值运算 (赋值)+=、 /= 关系和逻辑运算 ==(相等),!=(不相等),>(大于),<(小于), >=(大于等于) (小于等于) (逻辑或),&&(逻辑与) 分量运算->(数据成员),->*(指针型函数成员 其他运算,(关联语句)<<(输出流),>>(输入流)
可以被重载的运算符(双目) 算术运算 +(加),-(减),*(乘),/(除),%(取余) 位运算 <<(左移),>>(右移),|(或),&(与),^(异或) 赋值运算 =(赋值)+=、-=、 /=、*=、|=、&=、 ^= 关系和逻辑运算 ==(相等),!=(不相等),>(大于),<(小于), >= (大于等于),<=(小于等于), ||(逻辑或),&&(逻辑与) 分量运算 ->(数据成员),->*(指针型函数成员) 其他运算 ,(关联语句) <<(输出流), >>(输入流)