C++ Operator——Choose method.

来源:互联网 发布:闹铃软件 编辑:程序博客网 时间:2024/06/07 15:36


在运算符重载中,有友元函数重载成员函数重载两类。


当重载的运算符 左操作符 必须 是对象本身时,必须用成员函数重载。函数参数个数为该操作符操作数-1,传入的参数为“右”操作数。“左”操作数以this传入。

例子:

1: =、()、[ ]、->;

2: +=、-+……;

3: 一元操作符(++,--)。


当重载的运算符 左操作数 可以 是其他类型(如进行强制转换,或者指定为输入输出对象)时。必须用友元函数重载。函数参数为操作符操作数个数。

例子:

friend const A operator(const A &lhs,const A &rhs);
const A operator(const A &lhs,const A &rhs){ A add_res = lhs;return add_res += rhs;}

<<

friend ostream& operator<<(ostream& os ,const A& a);
ostream& operator<<(ostream& os ,const A& a){ os<<a.x<<endl<<a.y<<endl; return os;}