C + + cout introduction and implementation of their own cout

Source: Internet
Author: User
Tags protected constructor

The standard output stream in the C + + programming language interchange flow requires iostream support. Read as "c out ([si: ' a?t]".

Name

cout

Type

Std::ostream

Read as

"C Out"

Truth

std::cout.operator<< () function

Listen to speech using a sample

#include <iostream>

using namespace Std;

int main ()

{

int A;

cout << "Please enter a number, press ENTER to end" << Endl;

Cin >> A;

cout << a << Endl;

return 0;

}

The number entered by the user is stored in the variable a by CIN and is output through cout.

#include <iostream>

using namespace Std;

int main ()

{

cout << "hello,world!" << Endl;

return 0;

}//helloworld Example

Case study listening to speech

Because I have learned C before, so the other parts of this code in my opinion are still "normal", but cout is very unique: not a function, it does not seem that C + + special rules like if,for A class of special syntax "statement." Because it's just a preliminary introduction, the book simply says that cout is the "standard input output stream" object in C + + ... This is a very esoteric term for me. It's not over yet, and then I met Cin ... Because I do not know the details, from the time of use they are very anxious, a few to escape back to the C-era that concise printf (), after all, I can say: I am calling is a function. That has a long list of <<, >> things, what is the matter? I have always wanted to use them as a keyword, but it is not, and incredibly is in C + + language "Do" out of, Ah! But printf () began to criticize my program with a lot of kindness, "C-language traces are too heavy" ...

Later with the study in depth, finally probably understand the cout/cin/cerr/... Ghost trick: Those things are just mildly outnumbered "deceptive", in fact, is still a function call, but this function is a bit special, with operator overloading, to be exact (the following or cout as an example) is overloaded with the "<<" operator. Let's just let it show the true nature of the function, see the equivalent version of helloworld!:

#include <iostream>

using namespace Std;

int main ()

{

Cout.operator << ("hello,world!");

Cout.operator << (Endl);

return 0;

}

Compile and run, the result and the classic version of no two. The above program should be easier to understand: cout is an object of the Ostream class, it has a member operator function operator<<, and each time it is called the output device (usually the screen) output. Well, here's a question: Why is the function operator<< able to accept different types of data, such as Integer, float, string, even pointer, and so on?

I think you guessed it, yes, with operator overloading. Operator functions are basically the same as general functions, and can be overloaded arbitrarily. The designers of the standard library have already customized for us the overloaded versions of iostream::operator<< for a variety of C + + basic data types, which allows us beginners to enjoy cout<< "hello,world!" as soon as they come up. <<endl;

cout.operator<< ("hello,world!"). operator<< (Endl);

is considered "strong equivalent". Could it be written like this? Check with the compiler ... ok,noproblem!

And why is it possible to write multiple words in succession? Please see the following definition:

ostream& std::cout.operator<< ();

Note that the previous ostream& represents a reference to the returned object, that is, you can continue to cout

For CIN, it is an object of the IStream stream class, which overloads the >> operator, and uses roughly the same as cout

Skill Application listening to speech

Well, we have basically seen the essence of cout, we can move to achieve a cout of the simplified version (Lite), in order to differentiate, we have designed the Cout object named Myout,myout object belongs to the class Myoutstream. All we have to do is overload a series of different types of operator<< operator functions for the Myoutstream class, and for simplicity's sake, we only implement overloads for integral type (int) and string type (char*). In order to express our relationship with iostream, we no longer use the header file iostream, and use the printf function in the ancient stdio to output, the program is very simple, including the complete main function, are listed as follows:

#include//In C and some old C + + is stdio.h, the new standard in order to make the standard library

Header file differs from user header file, it is recommended to use no extension

version, for the original C library, do not use the extension when the header file name before adding C

Class Myoutstream

{

Public

Const myoutstream& operator << (intvalue) const;//overloading of integer variables

Const myoutstream& operator << (CHAR*STR) const;//for string type overloading

};

Const myoutstream& myoutstream::operator<< (intvalue) const

{

printf ("%d", value);

return* this;//Note this return ...

}

Const myoutstream& myoutstream::operator << (char* str) const

{

printf ("%s", str);

Return* this;//Also, take a look here ...

}

Myoutstream myout;//Global objects that serve us anytime, anywhere myout

int main ()

{

int a=2003;

char* mystr= "hello,world!";

Myout << mystr << "\ n";

return 0;

}

The myout we define is already in shape and can work for us. The notes in the program indicate two points that we should pay particular attention to: that is, after the operator<< function is executed, it always returns a reference to itself, the output is complete, and why is it superfluous?

Remember that strange cout.operator<< ("hello,world!"). operator<< (Endl)? What it does means we can write in a row.

cout<< "hello,world!" <<endl;

Instead of

cout<< "hello,world!";

cout<<endl;

Why does it even have to be written like this? Let's analyze: In order of execution, the system first calls cout.operator<< ("hello,world!"), and then what? Then cout.operator<< returns itself, meaning that a statement like return *this appears in the last line of the function, so cout.operator<< ("hello,world!") The result of the call returned to cout, followed by .operator<< (Endl), which is equivalent to cout.operator<< (Endl)-and then the next output, if there are many << operators down , the call will always go on ... Wow, isn't it smart? Now you understand the mystery of our myoutstream::operator<< last line!

Take a second look at the most exciting line in the main function:

myout<< "\ n"

We know that the last "\ n" can implement a newline, but we always use Endl in the C + + tutorial, which seems to be the same--what's so mysterious about it? Book, the book says Endl is a manipulator (manipulator), which not only implements the line-breaking operation, but also refreshes the output buffer. What do you mean? Originally after the output operation, the data is not immediately transmitted to the output device, but first into a buffer, when the appropriate time (such as the device is idle) and then passed by the buffer, can also be forced to refresh through the operator flush,ends, or unitbuf:

cout<< "hello,world!" << "Flush the screen now!!!" <<flush;

This way, before the program executes to operator<< (flush), it is possible that the preceding string data is still in the buffer instead of being displayed on the screen, but after executing operator<< (flush), The program forces the data in the buffer to be fully transported to the output device and emptied. And the operator Endl equivalent to << "\ n" <<flush;

However, it may appear that there is no difference between a manual refresh or a screen. But for output objects such as files, it is not the same: too frequent refresh means that always write disk, will affect the speed. So it is usually written in a certain number of bytes before refreshing, how to do? These are the operators that depend on them.

cout control to listen to speech

To use the following control, you need to include the header file "Iomanip" in the corresponding source file. That is, add the following code:

#include <iomanip>

---Description of the control character

Dec---Base is 10, followed by decimal output (system default form)

Hex---Base 16, followed by hexadecimal output

Oct---Base 8, followed by octal output

Setfill (c)---Set the fill character to C

Setprecision (n)---Set the precision of the real number to n bits

SETW (n)---Set the field width to n characters

Setiosflags (ios::fixed)---fixed floating-point display

Setiosflags (ios::scientific)---index indicates

Setiosflags (Ios::left)---left-justified

Setiosflags (ios::right)---right-aligned

Setiosflags (IOS::SKIPWS)---ignore leading whitespace

Setiosflags (ios::uppercase)---16 decimal capital output

Setiosflags (ios::lowercase)---16-digit lowercase output

Where: SETW set the width of the domain, use once to set once, other functions, set a permanent effect.

cout related information listen to voice

1 The type of cout is Ostream

2 Ostream uses a singleton mode,

Protected constructor, cannot create another object outside the class (tested with Ostream OS)

Copy construction Private, cannot construct new object through existing object (test with Ostream OS (cout))

Copy assignment private, (test with Cout=cout)

3 cout in namespace std, a using namespace STD is required before use, or std::cout

4 You can use a reference, or a pointer to this object, meaning to say, to use ostream as a function of the formal parameters, you must use a reference or pointer. Because the arguments must be cout, and there can be only one object.

5 cout<< object, the type of the object is expressed in Oo, if you want to use cout to print an object, that is cout<< object, you can use the following program

Friend ostream& operator<< (ostream& OS,

Const oo& C) {//Why must I use friend

return OS << C. member 1 << ":" <<c. member 2;

}

Operator Overloading listening speech

To use: Change the name of the member function/friend function to the operator operator.

Called when this is called

For example:

Class OBJ

{

Public

void operator--(int s)

{

cout <<s;

}

}

int main (void)

{

OBJ o;

o--4;

This prints out a 4来

return 0;

}

Other information listen to voice

Iostream family of C + +

Well, with all that said, what are the advantages of the C + + iostream family compared to the printf/scanf family of the d? First of all, type handling is more secure and intelligent, think of the "%d", "%f" and other descriptors in printf to deal with int, float and so on are superfluous and troublesome, in case the wrong is not good enough to die, and the second is more extensibility: If I define a new plural class complex, printf to it is powerless, at most can only output real, imaginary parts, and iostream use of <<, >> operators are overloaded, you just overload the relevant operators can be, and flow style is more natural and concise, is not it?

From http://wapbaike.baidu.com/item/cout?fr=aladdin&ref=wise&ssid=0&from=1086k&uid=0&pu=usm% 402%2csz%401320_1002%2cta%40iphone_2_5.1_2_6.8&bd_page_type=1&baiduid=cd36111fea588a3e401aa4880a8fde82 &tj=xv_1_0_10_title

C + + cout introduction and implementation of their own cout

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.