1.7 C++ stream insertion operator overloading

C++ stream insertion operator overloading

In C++, the stream insertion operator (<<) is an operator used to output data into a stream, and the stream insertion operator can be overloaded so that programmers can customize the way to output objects.

The general form of an overloaded stream insertion operator is as follows:
insert image description here
where, T is the custom type to be output, os is an output stream object of type std::ostream, and obj is the object of the custom type to be output.

The return value of the overloaded function is a reference of type std::ostream, representing the output stream object.

When overloading stream insertion operators, readers need to pay attention to the following points:

1. The overloaded function must be a friend function of the class or a global function.

2. The first parameter of the overloaded function must be a reference of type std::ostream.

3. The second parameter of the overloaded function must be a constant reference of the custom type to be output.

4. The overloaded function must return a reference of type std::ostream.

The following is the stream insertion operator overloading demo I wrote:
insert image description here
In the above demo, I defined a class named MyObject, and overloaded the stream insertion operator << in it.

The first parameter of the overloaded function is a reference of type std::ostream, representing the output stream object;

The second parameter is a reference of type const MyObject, representing the object to be output.

In the overloaded function, I insert a string into the output stream object os, which contains the value of the MyObject object, and finally return the output stream object os.

In the main function, I create a MyObject object obj and use the cout stream to output it to the standard output stream.

Compile and run the above demo results:
insert image description here

Guess you like

Origin blog.csdn.net/qq_40240275/article/details/131201038