11.3 Operator Functions as Class Members vs Global functions °运算符函数可以是成员函数或者全局函数 °当重载为类的成员函数时 非静态的类成员函数 class hugelnt HugeIntA t intA p HugeIntA. operator+( intA ) Hugelnt operator+( int ) 使用this指针隐性获取操作左值 °左操作数(或唯一的操作数)必须为该类对象(或对象引用) °将自动包含该类对象(或其引用)作为操作数,函数参数 个数等于运算符目数-1 0 2018, SEU. All rights reserved. 16
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 16 11.3 Operator Functions as Class Members vs. Global Functions 运算符函数可以是成员函数或者全局函数 当重载为类的成员函数时 非静态的类成员函数 class HugeInt { public: HugeInt operator+( int ); }; 使用this指针隐性获取操作左值 左操作数(或唯一的操作数)必须为该类对象(或对象引用) 将自动包含该类对象(或其引用)作为操作数,函数参数 个数等于运算符目数-1
11.3 Operator Functions as Class Members vs Global functions 当重载为全局函数时 HugeIntA intA °形式 operator+( HugeIntA, intA ) class hugelnt class HugeInt friend HugeInt operator+( int, const HugeInt&) public HugeInt operator+( int HugeInt operator+( int a, const HugeInt hugeintA hugeintA int a;
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 17 当重载为全局函数时 形式 class HugeInt { friend HugeInt operator+(const HugeInt &, int); }; 函数参数个数等于运算符的目数 全局函数: 是否访问私有数据 Friend(可访问私有数据)复习~~~ Non-friend 思考:必须重载为全局函数的情况 左操作数必须为一个基本类型对象 使运算符具有可交换性 HugeInteger + int 和 int + HugeInteger 成员函数+参数调换的全局函数 11.3 Operator Functions as Class Members vs. Global Functions 实例
11.3 Operator Functions as Class Members Vs. Global functions(对比) ° HugelntA+intA operator+( HugelntA, intA ) HugeIntA. operator+( intA )i lass Hugelnt t friend Hugelnt operator+( const Hugelnt & int ) class hugelnt t public Hugelnt operator+( int ) 0 2018, SEU. All rights reserved. 18
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 18 11.3 Operator Functions as Class Members vs. Global Functions (对比) HugeIntA + intA HugeIntA.operator+( intA ); class HugeInt { public: HugeInt operator+( int ); }; operator+( HugeIntA, intA ); class HugeInt { friend HugeInt operator+( const HugeInt &, int ); };
11.3 Operator Functions as Class Members vs Global functions o intB HugelntB operator+(intB, HugeIntB ) intBoperator+( HugeIntB ); lass hugelnt t friend Hugelnt operator+( int, const HugeInt &) 0 2018, SEU. All rights reserved. 19
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 19 11.3 Operator Functions as Class Members vs. Global Functions intB + HugeIntB intB.operator+( HugeIntB ); operator+( intB, HugeIntB ); class HugeInt { friend HugeInt operator+( int, const HugeInt & ); };
11.3 Operator Functions as Class Members vs Global Functions 设计原则 1.(),[],->和赋值(=+=,-=等)运算符必须重载为 成员函数 2.>>,<<和需要支持交换律( Commutative)的运算 符重载为全局函数 3.其余运算符可以选择重载为成员或全局函数 0 2018, SEU. All rights reserved. 20
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 20 11.3 Operator Functions as Class Members vs. Global Functions --- 设计原则 1. ( ), [ ], ->和赋值(=, +=, -=等)运算符必须重载为 成员函数 2. >>, <<和需要支持交换律(Commutative)的运算 符重载为全局函数 3. 其余运算符可以选择重载为成员或全局函数