1.8 C++ stream extraction operator overloading

C++ stream extraction operator overloading

In C++, the stream extraction operator (>>) is an operator used to extract data from a stream.

The stream extraction operator in C++ can be overloaded, so that programmers can customize the way of inputting objects, input custom data types more conveniently, and also make the input more flexible and convenient.

The general form of stream extraction operator overloading:

insert image description here
Among them, T is the custom type to be input, is is an input stream object of type std::istream, obj is the object of the custom type to be input.

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

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

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

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

In the overloaded function, I use the input stream object is to extract an integer from the input stream, assign it to the value member variable of the MyObject object, and finally return the input stream object is.

In the main function, I create a MyObject object obj, and use the cin stream to input the integer entered by the user into the MyObject object.

Then call the member function printValue() of the MyObject class to output the value of the MyObject object.

Compile and run the above demo results:

insert image description here

Guess you like

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