We know that the operator overload function can choose two forms (1) member function form (2) Global friend function form. So what should we choose?
Operators, such as operator[],operator=, can be overloaded only by member functions, as specified by the syntax first. While some operators can be overloaded with member functions, can also punch the global friend function overload, such as: + +,--,+,-,+=,-=, and so on, such as the use of member function overloading can also use the global friend function overload operator, we recommend the use of member function overloading, because this emphasizes the operator and class Union, In particular, when the two-tuple operator is overloaded, the operator works better when the left-hand operand is the current object.
However, sometimes the operand to the left of the operator is a different object, which usually occurs when the input output stream operator overloads,operator<<,operator>>. The left side of the operator is a stream object, not the current object (the current object is the object that invokes the operator function), and the member function overload operator cannot be loaded at this point because the member function overloads the operator, which is the operand of the current object.
code example:
1 classintarray{2 enum{size=5};3 intM[size];4 Public:5 Intarray () {6memset (I,0, Size*sizoef (*i));7 8 }9 int&operator[](intindex) {Ten One if(index<0&&index>=size) Exit (0); A returnI[index]; - } - theFriend ostream&operator<< (ostream& out,Constintarray&aRef);//The operand on the left is a stream object, so it cannot be overloaded with member functions, but can only be overloaded with a meta function -Friend istream&operator>> (istream&inch,Constintarray&aRef); - }; - +ostream&operator<< (ostream& out,Constintarray&ared) { - for(intI=0; i<aref.size;i++){ + out<<Ared.m[i]; A if(i!=size-1) at out<<","; - } - out<<Endl; - return out; - - } in - toistream&operator>> (istream&inch,Constintarray&ared) { + - for(intI=0; i<aref.size;i++) the inch>>Aref.m[i]; * return inch; $ Panax Notoginseng}
Operator Overloading (iii)