C ++ input and output operators are overloaded.

Source: Internet
Author: User

C ++ input and output operators are overloaded.

C ++ can use stream extraction operators> and stream insertion operators <to input and output built-in data types. We can overload stream extraction operators and stream insertion operators to operate on custom data types such as objects.

Here, it is very important to declare the operator overload function as a friend function of the class, so that we can directly call the function without creating an object.

The following example demonstrates how to overload the extraction operator> and insert operator <.

# Include

Using namespace std;

Class Person {

Public:

Person (const char * str): name (str ){}

Int GetAge (){

Return this-> age;

}

/* Friend functions declared as Classes */

Friend ostream & operator <(ostream & output, Person & p ){

Output <p. name <endl;

Return output;

}

Friend istream & operator> (istream & input, Person & p ){

Input> p. age;

Return input;

}

Private:

Const char * name;

Int age;

};

Int main ()

{

Person p ("Tom ");

/* Overload output name */

Cout <p;

/* Overload input age */

Cin> p;

/* Output age */

Cout <p. GetAge () <endl;

Return 0;

}

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.