In C + +, we want to print the class information, need to overload << operator, this blog will describe how to overload << operator print class messages. and introduce some of the rules and reasons for doing so. overload << operator Print custom class information
We use code to explain: we define a person class that wants to print out the age attribute of the person class instance.
Person
{
private:
int age_;
Public:
void setage (int age)
{
Age_ = age;
}
}
int main ()
{person
A;
A.setage (ten);
cout << a << endl;
}
This write will certainly error, run failed (header file references, namespaces, etc. lazy did not write, do not care about these details). We want cout << A to automatically print out age.
Let's write this, add one more overload << operator method:
Class person
{
int age_;
Public:
void setage (int age)
{
This->age_ = age;
}
Friend Ostream &operator<< (ostream &stream, const person &p)
{
stream << P.age_ <& Lt Endl;
return stream;
}
;
int main ()
{person
A;
A.setage (ten);
cout << a << endl;
}
Run the program to see 10 printed out.
Here, we use a friend function to overload the << operator, and this friend function has a fixed format:
Friend Ostream &operator<< (ostream &stream, const person &p)
{
stream << P.age_ < < Endl;
return stream;
}
In order to be consistent with the IO standard library, to return a reference to a Ostream object, accept two parameters, the first parameter is an application to a Ostream object, the second parameter is a reference to a class type object that you want to print, and you want to cout<< print a person class, The second argument passes in a reference to a person class, which is also defined as a friend class. Why do you define this << operator overload as a friend class
Syntactically, we can actually define this function as a class member function, as follows:
Class person
{
int age_;
Public:
void setage (int age)
{
This->age_ = age;
}
Ostream &operator<< (ostream &stream)
{
stream << age_ << Endl;
return stream;
}
;
int main ()
{person
A;
A.setage (one);
A << cout;
}
As shown in the code, we remove the keyword friend, remove the second parameter, and then use a << cout to print the class information. As you can see, if this definition is the opposite of other types of output operators.
The following refers to a passage in a c++primer:
Conversely, if you want to use overloaded operators to provide IO operations for that type, you must define them
is not a member function. IO operators typically read and write to non-public data members, so classes typically associate IO
Operation Subscript character is a friend.
In other words, the IO operator overloads the function, which is often defined as a friend function.