The overloaded stream insert operator and stream extraction operator in C + + programming _c language

Source: Internet
Author: User

C + + Flow insert operator "<<" and stream extraction operator ">>" is C + + in the class library provided, all C + + compiler system in the class library provides input stream class IStream and output stream class Ostream. CIN and cout are objects of the IStream class and the Ostream class respectively. The "<<" and ">>" have been overloaded in the header file provided by the class library as the stream insert operator and stream extraction operator, which can be used to output and enter data of the C + + standard type. Therefore, the use of "cout<<" and "cin>>" to the standard type of data input and output, to use the #include head file included in this program file.

The user-defined type of data cannot be exported and entered directly with "<<" and ">>". If you want to use them to output and enter data of the type you declare, you must overload them.

The functions that are overloaded with the << and >> are as follows:

  IStream & operator >> (IStream, custom class &);
  Ostream & operator << (ostream, custom class &);


That is, the first parameter and function of a function with overloaded operator ">>" must be of type istream&, and the second is the class to be entered. The first parameter and function of the overloaded "<<" function must be of type ostream&, and the second is the class for which you want to output operations. Therefore, you can only use overloaded ">>" and "<<" functions as friend functions or normal functions, not as member functions.
overloaded Stream insert operator ' << '

In a program, people want to use the insert operator "<<" to output information about the object of the class that the user declares, which requires the overloaded stream insert operator "<<".

[Example] output complex numbers with overloaded ' << '.

#include <iostream>
using namespace std;
Class Complex
{public
  :
  Complex () {real=0;imag=0;}
  Complex (double r,double i) {real=r;imag=i;}
  Complex operator + (Complex &c2); Operator "+" overload is member function
  friend ostream& operator << (ostream&,complex&);//Operator "<<" overload is a friend function
  Private:
  double real;
  Double imag;
};
Complex Complex::operator + (Complex &c2)//define operator "+" overloaded function
{return
  Complex (REAL+C2.REAL,IMAG+C2.IMAG);
}
ostream& operator << (ostream& output,complex& C)//define operator "<<" overloaded function
{
  output<< "(" <<c.real<< "+" <<c.imag<< "i)" <<endl;
  return output;
}
int main ()
{
  Complex C1 (2,4), C2 (6,10), C3;
  C3=C1+C2;
  cout<<c3;
  return 0;
}

Note that when running in Visual C + + 6.0 environments, the first line must be changed to #include <iostream.h>, and the 2nd line is deleted, otherwise the compilation cannot pass. The results of the operation are:

(8+14i)

You can see that after the operator "<<" overload, "<<" in the program not only outputs standard type data, but also outputs the user-defined class object. With "COUT<<C3", the value of complex object C3 can be output in plural form. The form is intuitive, the readability is good, easy to use.

Here are some instructions on how to implement operator overloading. The operator "<<" is overloaded in the program, and the parameter output in the operator overload function is a reference to the Ostream class object, and the parameter name output is arbitrary from the user. Analyze the last second line of the main function:

  cout<<c3;


The left side of the operator "<<" is cout, and cout is the Ostream class object mentioned earlier. "<<" to the right is C3, it is the complex class object. Because the overloaded function of operator "<<" has been declared as a friend function of the complex class, the compilation system interprets "COUT<<C3" as

  operator<< (Cout, C3)


That is, with cout and C3 as arguments, the following operator<< function is called:

  ostream& operator<< (ostream& output,complex& c)
  {
    output<< "(" <<c.real< < "+" <<c.imag<< "i)" <<endl;
    return output;
  }


When calling a function, the parameter output becomes a reference to the cout, and parameter C becomes a reference to the C3. So the process of calling a function is equivalent to executing:

Cout<<″ (″<<c3.real<<″+″<<c3.imag<<″i) ″<<endl; return cout;


Note that "<<" in the previous line is a predefined stream caret for C + +, because the operand on the right side is a string constant and a double type of data. Executes the cout statement to output the plural form of information. Then execute the return statement.

Please think, what is the function of return output? The answer is to be able to insert information continuously into the output stream. Output is an object of the Ostream class, which is a reference to the argument cout, that is, cout the output by sending the address to the same storage unit, or output is cout alias. Therefore, return output is returned cout, the output stream cout the status quo, that is, the current status of the output stream.

Where would you like to go? I was just doing it.

  cout<<c3;


The return value of the known cout<<c3 is the current value of the cout. If you have the following output:

  cout<<c3<<c2;


First deal with

  Cout<<c3


That

  (COUT<<C3) <<c2;


The result of execution (COUT<<C3) is the stream object cout with the new content, so (COUT<<C3) <<C2 is equivalent to cout (new value) <<c2. On the left side of the operator << is the Ostream class object cout, and the complex class object C2 on the right, the operator "<<" overload function is called again, and then the C2 data is inserted into the output stream. Now you can understand why C + + specify that the first parameter and function of the operator "<<" overload function must be a reference to the Ostream type, in order to return the current value of the cout for continuous output.

Please note that the "<<" is a stream caret of the standard type of data, and under what circumstances "<<" is an overloaded stream insert. Such as

  cout<<c3<<5<<endl;


Underlined is the invocation of the overloaded stream insert, followed by two "<<" is not an overloaded stream caret, because its right side is not the complex class object but the standard type of data, and is handled with a predefined stream insert.

It is also important to note that in this program, the operator "<<" overload function is defined in the complex class as a friend function, so the overloaded operator can only be used when outputting the complex class object, and is not valid for other types of objects. Such as

  cout<<time1; Time1 is a time class object and cannot use overloaded operators for complex classes


Overloaded Stream extraction operator ">>"

The purpose of the C + + predefined operator ">>" is to extract data from an input stream, such as "cin>>i;" Represents the extraction of an integer from the input stream to the variable i (assuming I is defined as int). The purpose of the overloaded stream extraction operator is to use ">>" to enter information for an object of a custom type.

[Example] on the basis of the above example, add the overloaded stream extraction operator ">>", enter the plural with "cin>>" and output the plural with "cout<<".

#include <iostream>
using namespace std;
Class Complex
{public
  :
  friend ostream& operator << (ostream&,complex&);//declaring overloaded operators << "
  friend istream& operator >> (istream&,complex&);//Declare overloaded operator" >> "
  private:
  double Real;
  Double imag;
};
ostream& operator << (ostream& output,complex& C)//define overloaded operator "<<"
{
  output<< "( "<<c.real<<" + "<<c.imag<<" i) ";
  return output;
}
istream& operator >> (istream& input,complex& C)//define overloaded operator ">>"
{
  cout<< " Input real part and imaginary part of complex number: ";
  input>>c.real>>c.imag;
  return input;
}
int main ()
{
  Complex c1,c2;
  cin>>c1>>c2;
  cout<< "c1=" <<c1<<endl;
  cout<< "c2=" <<c2<<endl;
  return 0;
}

The operating conditions are as follows:

Input real part and imaginary part of complex number:3 6↙ input real part and imaginary part of
complex number:4 2/>c1= (3+6i)
c2= (4+10i)

The results of the above operation are undoubtedly correct, but not perfect. When the imaginary part of a complex number is positive, the result of the output is no problem, but if the imaginary part is negative, it is not ideal, please observe the output.

Input real part and imaginary part of complex number:3 6↙ input real part and imaginary part of
complex number:4 c6/>c1= (3+6i)
c2= (4+-10i)

According to the first debugging through, finally perfect principle, can make necessary changes to the procedure. Modify the overloaded operator "<<" function as follows:

ostream& operator << (ostream& output,complex& c)
{
  output<< "(" <<c.real;
  if (c.imag>=0) output<< "+" If the imaginary part is positive, add the "+" number
  output<<c.imag<< "i)" before the imaginary part <<endl; When the imaginary part is negative, the "+" number is not added before the imaginary part
  .


In this way, the last behavior of the run-time output c2= (4-10i).

As you can see, in C + +, operator overloading is important and practical. It makes the design of the class more colorful, expanded the function of the class and the scope of use, so that the program easy to understand, easy to operate on the object, it embodies for the sake of the user, user-friendly ideas. With operator overloading, after declaring a class, people can use their own declared classes as if they were using a standard type. Class declarations are often once and for all, and with good classes, users do not have to define many member functions in a program to perform certain operations and input and output functions, making the main function more simple and readable. A good operator overload can embody object-oriented programming ideas.

You can see the importance of using references (reference) in operator overloading. Using references as parameters of a function can be used to invoke a function in the process of not using the method of passing the value of the actual combination, but through the way to make the formal parameters of the argument is an alias, so do not generate a temporary variable (a copy of the argument), reduce the time and space overhead. In addition, if the return value of an overloaded function is a reference to an object, instead of a constant, it refers to the object represented, which can appear on the left side of the assignment number as the left value, and can be assigned to or participate in other operations, such as preserving the current value of the cout stream so that it can be used continuously << "Output). However, use a reference with caution, because modifying a 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.