Detailed usage of C ++ ostream

Foreword

In C ++, ostream represents the output stream , the English "output stream" for short. Common in C ++ output stream object is the standard output stream cout, ostream few custom objects, and more direct use cout. So ostream what use is it, look at a scene:

1 class CPoint
2 {
3 public:
4     CPoint(int x_,int y_):x(x_),y(y_){}
5     int x,y;
6 };

For example ... This defines a simple class CPoint, if after we instantiate the class, you want to print the value of the object:

1 CPoint point(1,2);
2 cout << point;

Obviously, this is written will complain because "<<" can only output integer, real, and other common types. Error as follows:

 

 The ostream appears just to solve this problem.

In C ++ ostream this type, usually as a class friend function appear in a << overloaded operation. Next we look at an example of how to make a normal stream output by modifying the above normal.

 1 class CPoint
 2 {
 3 public:
 4     CPoint(int x_,int y_):x(x_),y(y_){}
 5 
 6     friend ostream & operator <<(ostream & os,const CPoint & p){
 7         return os << "x = "<<p.x  << " y = "<< p.y << endl;
 8     }
 9 
10     int x,y;
11 };//类后面要记得加;

In CPoint we overloaded << operator can be allowed to normal output.
The method may also be extended to many other places, especially useful when a custom type output, written are the same, as long as the operator << overload, to use together with ostream.

Guess you like

Origin www.cnblogs.com/loliconinvincible/p/12554115.html