Object Assignment-assignment operator overloading
An assignment operator function is a special member function defined in a class
The typical implementation method:
operator= (const ClassName & Right) { if ( This! = & Right) {
Copy the contents of right to the current object
} return *this;}
#include <iostream>using namespacestd;classtest{intID; Public: Test (inti): ID (i) {cout <<"Obj_"<< ID <<"created\n"; } Test&operator= (Consttest&Right ) { if( This= = &Right ) cout<<"same obj!"<<Endl; Else{cout<<"Obj_"<< ID <<"=obj_"<< right.id <<Endl; This->id =right.id; } return* This; }};intMain () {Test A (1), B (2); cout<<"a = a:"; A=A; cout<<"a = B:"; A=b; return 0;}
Declaration of overloaded functions for stream operators
istream& operator>> (istream& in, test& DST);
ostream& operator<< (ostream& out, const test& SRC);
Note:
The function name is:
Operaotor>> and operator<<
The return value is:
istream& and Ostream&, all references
Arguments are: a reference to the Stream object, and a reference to the target object. For the output stream, the target object is still a constant
#include <iostream>using namespacestd;classtest{intID; Public: Test (inti): ID (i) {cout<<"Obj_"<< ID <<"created\n"; } Friend IStream&operator>> (istream&inch, test&DST); Friend Ostream&operator<< (ostream& out,Consttest&src);};//Note: The following two stream operator overloaded functions can access private members directly because they are declared as friend functionsistream&operator>> (istream&inch, test&DST) { inch>>dst.id; return inch;} Ostream&operator<< (ostream& out,Consttest&src) { out<< src.id <<Endl; return out;}intMain () {Test obj (1); cout<<obj; CIN>>obj; cout<<obj;}
C + + Programming Method 2: Basic Syntax 2