Non-member operators
When the left side of the operator is a different class, it is not possible to overload the operator into the class.
IostreamOperatorOverloading.cpp
/*** book: "thinkinginc++" * Function: Non-member operator * Time: October 4, 2014 14:23:25* Author: cutter_point*///When the left side of the operator is a different class, you cannot overload the operator into the class. #include ". /require.h "#include <iostream> #include <sstream> #include <cstring> usingnamespace std; classintarray{enum {sz=5}; int I[sz];p ublic://bar array I initialize, bar the number of sz*sizeof (*i) in the array is initialized to 0 intarray () {memset (i, 0, sz*sizeof (*i));} overloaded [] Operator//The left parameter is this class, that is, Intarray[x] Representative i[x]; int& operator [] (int x) {require (x >= 0 && x < sz, "intarray::operator[] out of range"); return i[x]; }//Two friend function friend ostream& operator << (ostream& OS, const intarray& IA); Friend istream& operator >> (istream& is, intarray& ia);}; Ostream&operator << (ostream& OS, const intarray& IA) {for (int i=0; i<ia.sz; ++i) {OS <<ia.i[i]; if (i! = ia.sz-1) os<< ","; } os<<endl; return OS;} Enter friend Istream&operator >> (istream& is, intarray& ia) {for (int i=0; i<ia.sz; ++i) is>>ia.i[i]; return is;} int main () {StringStream input ("47 34 56 92103"); Bar character stream and this string bind Intarray I; input>>i; The bound string is entered into I, each time separated by a space i[4]=-1; cout<<i; return 0;}
Please congratulate me on being an uncle.
"Thinkinginc++" 61, non-member operators