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;
}