C + + Programming Method 2: Basic Syntax 2

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.