C ++ heavy-duty stream insertion and stream extraction operators, heavy-duty operators

Source: Internet
Author: User

C ++ reloads the stream insertion operator and stream extraction operator [convert], and reloads the operator

C ++'s stream insertion operator <and stream extraction operator> is provided by C ++ in the class library, all C ++ compilation systems provide input stream class istream and output stream class ostream in the class library. Cin and cout are the objects of the istream class and ostream class respectively. The header files provided by the class library have been overloaded with "<" and ">" to serve as the stream insertion and stream extraction operators, it can be used to output and input C ++ standard data. Therefore, if you use "cout <" and "cin>" to input and output standard-type data, you must use # include to include the header file in this program file.

User-Defined data types cannot be output or input directly using <"and">. If you want to use them to output and input data of the declared type, you must reload them.

The Function Format for "<" and ">" is as follows:
Istream & operator> (istream &, custom Class &);
Ostream & operator <(ostream &, custom Class &);
That is, the first parameter and function type of the function with the overload operator ">" must be istream & type, and the second parameter is the class to be input. The first parameter and function type of the function with the "<" overload must be ostream & type, and the second parameter is the class for output operations. Therefore, you can only use functions with ">" and "<" as friend functions or common functions, rather than defining them as member functions.

Reload stream insertion operator "<"

In a program, people want to use the insert operator "<" to output information about the class objects declared by the user. Therefore, the stream insertion operator "<" needs to be overloaded ".

[Example 10.7] on the basis of example 10.2, use the overloaded "<" to output the plural number.

  1. # Include <iostream>
  2. Using namespace std;
  3. Class Complex
  4. {
  5. Public:
  6. Complex () {real = 0; imag = 0 ;}
  7. Complex (double r, double I) {real = r; imag = I ;}
  8. Complex operator + (Complex & c2); // The operator "+" is overloaded as a member function.
  9. Friend ostream & operator <(ostream &, Complex &); // The operator "<" is overloaded as a friend function.
  10. Private:
  11. Double real;
  12. Double imag;
  13. };
  14. Complex: operator + (Complex & c2) // defines the operator "+" to overload the function.
  15. {
  16. Return Complex (real + c2.real, imag + c2.imag );
  17. }
  18. Ostream & operator <(ostream & output, Complex & c) // defines the operator "<" to overload the function.
  19. {
  20. Output <"(" <c. real <"+" <c. imag <"I)" <endl;
  21. Return output;
  22. }
  23. Int main ()
  24. {
  25. Complex c1 (2, 4), c2 (6, 10), c3;
  26. C3 = c1 + c2;
  27. Cout <c3;
  28. Return 0;
  29. }

Note: When running in the Visual C ++ 6.0 environment, you need to change the first line to # include <iostream. h> and delete the first line. Otherwise, the compilation fails. The running result is:
(8 + 14i)

After the operator "<" is overloaded, "<" can be used in the program to output not only standard type data, but also user-defined class objects. "Cout <c3" can be used to output the value of c3 in the form of a plural object. The format is intuitive, readable, and easy to use.

The following describes how to implement Operator overloading. The operator "<" is overloaded in the program. The output parameter in the operator overload function is a reference to an ostream object, and the output parameter is user-initiated. Analyze the second line of the main function:
Cout <c3;
The left side of the operator "<" is cout. As mentioned above, cout is an ostream class object. The right side of "<" is c3, which is a Complex object. Since the overload function of the operator "<" has been declared as a friend function of the Complex class, the compilation system interprets "cout <c3"
Operator <(cout, c3)
The following operator is called using cout and c3 as real parameters <function:
Ostream & operator <(ostream & output, Complex & c)
{
Output <"(" <c. real <"+" <c. imag <"I)" <endl;
Return output;
}
When a function is called, the output parameter is a reference of cout, and the c parameter is a reference of c3. Therefore, the process of calling a function is equivalent to executing:
Cout <"(" <c3.real <"+" <c3.imag <"I)" <endl; return cout;
Note that the "<" in the previous row is a pre-defined stream plug-in C ++, because its right operand is String constant and double type data. Execute the cout statement to output information in the plural form. Then execute the return statement.

What is the function of return output? The answer is that information can be inserted continuously into the output stream. Output is an object of the ostream class. It is a reference of the cout parameter, that is, cout transfers the address to the output so that the two share the same storage unit, or the output is the cout alias. Therefore, return output is the return cout, which returns the current status of the output stream cout, that is, the current status of the output stream.

Where can I go back? Just executed
Cout <c3;
It is known that the return value of cout <c3 is the current value of cout. If the following output is available:
Cout <c3 <c2;
Process first
Cout <c3
That is
(Cout <c3) <c2;
The result of cout <c3) execution is the stream object cout with new content. Therefore, cout <c3) <c2 is equivalent to cout (new value) <c2. If the operator "<" is the ostream Class Object cout on the left and the Complex Class Object c2 on the right, call the operator "<" to reload the function again, and then insert c2 data to the output stream. Now we can understand why C ++ requires that the first parameter and function type of the operator "<" overload function must be referenced by the ostream type, to return the current cout value for continuous output.

Please note that "<" is the stream insertion operator of the standard data type and "<" is the reload stream insertion operator. For example
Cout <c3 <5 <endl;
The underlined one is the calling of the reloaded stream plug‑in. The next two "<" parameters are not the reloaded stream plug‑in, because they are not Complex class objects but standard-type data on the right, it is processed with a predefined stream plug-in.

Another note is that in this program, the Complex class defines the operator "<" overload function as a friend function, therefore, the overloaded operator can be used only when Complex class objects are output, which is invalid for other types of objects. For example
Cout <time1; // time1 is a Time-Class Object and cannot use heavy-duty operators for the Complex class

Heavy stream extraction operator ">"

The predefined C ++ operator ">" is used to extract data from an input stream, such as "cin> I; "indicates to extract an integer from the input stream and assign it to variable I (assuming I is defined as int type ). The purpose of the overload stream extraction operator is to use ">" to enter information about an object of the custom type.

[Example 10.8] on the basis of example 10.7, the heavy-load stream extraction operator ">" is added, "cin>" is used to input the plural value, and "cout <is used to output the plural value.

  1. # Include <iostream>
  2. Using namespace std;
  3. Class Complex
  4. {
  5. Public:
  6. Friend ostream & operator <(ostream &, Complex &); // declares the overloaded operator "<"
  7. Friend istream & operator> (istream &, Complex &); // declare the overload operator ">"
  8. Private:
  9. Double real;
  10. Double imag;
  11. };
  12. Ostream & operator <(ostream & output, Complex & c) // defines the heavy-duty operator "<"
  13. {
  14. Output <"(" <c. real <"+" <c. imag <"I )";
  15. Return output;
  16. }
  17. Istream & operator> (istream & input, Complex & c) // defines the heavy-duty operator ">"
  18. {
  19. Cout <"input real part and imaginary part of complex number :";
  20. Input> c. real> c. imag;
  21. Return input;
  22. }
  23. Int main ()
  24. {
  25. Complex c1, c2;
  26. Cin> c1> c2;
  27. Cout <"c1 =" <c1 <endl;
  28. Cout <"c2 =" <c2 <endl;
  29. Return 0;
  30. }

The running status is as follows:
Input real part and imaginary part of complex number: 3 6
Input real part and imaginary part of complex number: 4 10
C1 = (3 + 6i)
C2 = (4 + 10i)

The above running results are undoubtedly correct, but they are not perfect. When the imaginary part of the input complex is a positive value, the output result is correct. However, if the imaginary part is a negative value, it is not ideal. Observe the output result.
Input real part and imaginary part of complex number: 3 6
Input real part and imaginary part of complex number: 4-10
C1 = (3 + 6i)
C2 = (4 +-10i)

The program can be modified as necessary based on the principle of passing the debugging and final perfection. Modify the overload operator "<" as follows:

  1. Ostream & operator <(ostream & output, Complex & c)
  2. {
  3. Output <"(" <c. real;
  4. If (c. imag> = 0) output <"+"; // when the imaginary part is a positive number, add the "+" sign before the imaginary part.
  5. Output <c. imag <"I)" <endl; // when the imaginary part is negative, the "+" sign is not added before the imaginary part.
  6. Return output;
  7. }

In this way, the last line output during the runtime is c2 = (4-10i ).

In C ++, Operator Overloading is very important and practical. It makes the design of the class more colorful, expands the function and scope of use of the Class, makes the program easy to understand, easy to operate on the object, it embodies the thought of making it easier for users to use. With operator overloading, people can use their own declared classes just like using standard types. Class declaration is always done once and for all. With a good class, you do not have to define many member functions in the program to complete some operations and input/output functions, making the main function easier to read. Good operator overloading can reflect the idea of object-oriented programming.

We can see the importance of using reference in Operator overloading. When calling a function, you can use the reference as the parameter of a function to make the parameter an alias of a real parameter instead of passing the value, therefore, no temporary variables (copies of real parameters) are generated, reducing the overhead of time and space. In addition, if the returned value of the overload function is an object reference, the returned value is not a constant, but an object represented by the reference, it can appear on the left side of the value assignment and become the left value ), values can be assigned or involved in other operations (such as retaining the current value of the cout stream to allow continuous use of the "<" output ). However, be careful when using the reference, because modifying the reference is equivalent to modifying the object it represents.

Related Article

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.