C ++ getting started -- Analysis of cout

Source: Internet
Author: User

#include

usingnamespacestd;

intmain()

{

cout<<"Hello,World!"<

return0;

}

Since I have learned C before, other parts of this Code are still "normal" in my opinion, but cout is very unique: neither function nor function, it does not seem that C ++ specifically stipulates "statements" such as if and for with special syntax ". Because it is only a preliminary introduction, the book simply says that cout is a "standard input/output stream" Object in C ++ ...... This is a very profound term for me. This is not complete, and then we met cin ...... I am not sure what I want to do, and I am very scared when I use them. I want to escape from the concise printf () in the C era. After all, I can say that I am calling a function. So there's a long string of <,>. What's the matter? I have always wanted to treat them as keywords, but they are not. They are actually made in C ++! But when printf () was used more often, some people began to criticize my program "the C language trace is too heavy "......

Later, with the further study, I finally understood cout/cin/cerr /... the tricks: those things are just changing the way they are "cool", but in the end they are still called functions. However, this function is special and uses Operator overloading. To be exact, the following uses cout as an example) the <operator is overloaded. Now let's show it the true nature of the function. Please refer to HelloWorld! Equivalent version:

#include

usingnamespacestd;

intmain()

{

cout.operator<<("Hello,World!");

cout.operator<<(endl);

return0;

}

Compiling and running. The result is no different from that of the classic version. The above program should be easier to understand: cout is an iostream class object, which has a member operator function operator <, each time a call is made, it will output something to the output device (usually the screen. Well, here is a question: why can the operator function <accept different types of data, such as integer, floating point, string, and even pointer?

I guess you have already guessed it. That's right, it's to use the operator to reload it. Operator Functions are basically the same as general functions and can be reloaded as needed. The designers of the standard library have already customized iostream: operator <for the overloaded versions of various C ++ basic data types, this allows beginners to enjoy cout <"Hello, World! "<

Cout. operator <("Hello, World! "). Operator <(endl );

Is considered as "strongly equivalent ". Can I write it like this? Confirm with the compiler ...... OK, NoProblem!

Well, we have basically seen the essence of cout. Now we can start to implement a simplified version (Lite) of cout by ourselves, we name the cout object myout, and the class to which the myout object belongs is MyOutstream. What we need to do is to reload a series of operator operators of different types for the MyOutstream class <operator function. For simplicity, Here we only implement the integer and string types (char *). In order to express the disconnection from iostream, we no longer use the header file iostream, but use the printf function in the old stdio for output. The program is very simple, including the complete main function, which is listed as follows:

# Include // stdio. h In C and some ancient C ++. The new standard aims to make the standard library

// The header file is different from the user header file. We recommend that you do not use an extension.

// Version. For the original C library, c must be added before the header file name without the extension.

classMyOutstream

{

public:

ConstMyOutstream & operator <(intvalue) const; // overload of Integer Variables

ConstMyOutstream & operator <(char * str) const; // reload the string type

};

constMyOutstream&MyOutstream::operator<<(intvalue)const

{

printf("%d",value);

Return * this; // pay attention to this return ......

}

constMyOutstream&MyOutstream::operator<<(char*str)const

{

printf("%s",str);

Return * this; // Similarly, pay attention to it here ......

}

MyOutstreammyout; // Global Object myout for our services anytime, anywhere

intmain()

{

inta=2003;

char*myStr="Hello,World!";

myout< return0;

}

Our myout has already taken shape and can work for us. Note in the program that we should pay special attention to the following two points: operator <after the function is executed, it always returns a reference of itself, and the output has been completed. Why do we need to do this?

Remember that cout. operator <("Hello, World! "). Operator <(endl? Its implementation means that we can write

Cout <"Hello, World! "<

Instead

Cout <"Hello, World! ";

Cout <

Why can it be connected and written like this? Let's analyze: In the execution order, the system first calls cout. operator <("Hello, World! "), Then? Then cout. operator <will return it, that is, the last line of the function will contain a statement similar to return * this, so cout. operator <("Hello, World! ") The call result returns cout, followed. operator <(endl), which is equivalent to cout. operator <(endl) -- then the next output will be made. If there are many <operators down, the call will continue ...... Wow, isn't it smart? Now you understand the secrets of MyOutstream: operator <the last line!

Pay attention to the most exciting line in the main function:

Myout < We know that the last "" appears to implement a line feed, but we always intentionally or unintentionally let us use endl when using C ++, the two seem to be the same-what exactly is mysterious? In the book, The endl is a manipulator, which not only implements line feed operations, but also refreshes the output buffer. What does it mean? After the output operation, the data is not immediately transmitted to the output device, but first enters a buffer zone. When the appropriate time (such as when the device is idle), the data is passed in by the buffer zone, you can also force refresh by using the operator flush:

Cout <"Hello, World! "<" Flushthescreennow !!! "<

In this way, when the program is executed before the operator <(flash), it is possible that the previous string data is still in the buffer rather than on the screen, but after the operator <(flash, the program will forcibly move all the data in the buffer zone to the output device and clear it. The operator endl is equivalent to <"" <

However, the screen may show that manual refresh is not much different. However, output objects such as files are not the same: too frequent refresh means that writing a disk always affects the speed. Therefore, it is usually written to a certain number of bytes before refreshing. How can this problem be solved? These operators are used.

Well, after talking about this, what are the advantages of C ++'s iostream family compared with C's print/scanf family? First, data processing is safer and more intelligent. Think about how to deal with int, float, and other specifiers such as "% d" and "% f" in printf, in case of errors, it will still die. Secondly, it is more scalable: If I define a new Complex category Complex, printf can't do anything about it, at most it can only output the real and virtual parts separately, iostream's <,> operators can be reloaded. You only need to reload the related operators. Moreover, the stream style is also concise, isn't it?

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.