Several gains from C ++ Primer Plus -- (11), primerplus

Source: Internet
Author: User

Several gains from C ++ Primer Plus -- (11), primerplus

This article mainly introduces the advantages and disadvantages of conversion functions and briefly introduces Stream and iostream files.

 

Because the Stonewt class of the previous article is still used in this article, the code is given first.

<span style="font-size:18px;">ifndef STONEWT_Husing std::cout;#define STONEWT_Hclass Stonewt{    public:        Stonewt(double lbs,int stn);        {            stone=stn;            pds_left=lbs;            pounds=stn*Lbs_per_stn;        }                Stonewt(double lbs)        {            stone=int(lbs)/Lbs_per_stn;//integer divition            pds_left=int(lbs)%Lbs_per_stn+lbs-int(lbs);            pounds=lbs;        }                stonewt() {stone=pounds=pds_left=0;};        virtual ~Stonewt() {};        void show_lbs() const {cout<<pounds<<"pounds\n";};        void show_stn() const {cout<<stone<<"stone,"<<pds_left<<"pounds\n";};    private:        enum{Lbs_per_stn=14};        int stone;        double pds_left;        double pounds;};#endif // STONEWT_H</span>


11.1 conversion functions

From the previous article, we know that by implicit conversion, we want to assign a value of the double type to the Stonewt object. However, can we do the opposite conversion? That is

<span style="font-size:18px;">Stonewt wolfe(285.7);double host=wolfe;//possible??</span>


To perform this opposite conversion, you must use a special C ++ operator function --Conversion functions. Conversion functions are user-defined forced type conversions. They can be used as they are forced type conversions. If a conversion function is defined, you can perform the following conversions:

<span style="font-size:18px;">Stonewt wolfe(285.7);double host=double(wolfe);double star=(double)wolfe;</span>


11.2 create a Conversion Function

To convert the typename type, use this form of Conversion Function

<span style="font-size:18px;">operator typename();</span>

  • Note the following points:
  • The conversion function must be a class method;
  • The return type cannot be specified for the conversion function;
  • The conversion function cannot have parameters.

Here we can provide the Stonewt conversion function.

<span style="font-size:18px;">Stonewt::operator int() const{  return int(pounds+0.5);}Stonewt::operator double() const{  return pounds;}</span>


After that, it will be legal to write such a statement.

<span style="font-size:18px;">Stonewt poppins;long gone=(double)poppins;long gone=int(poppins);</span>


11.3 disadvantages of conversion functions

Like the conversion constructor, the conversion function also has its disadvantages. The problem with functions that provide automatic and implicit conversions is that the conversion function may also be converted if you do not want to perform the conversion. To avoid this situation, we can use explicit. With the following declaration, you must declare the operator as an explicit

<span style="font-size:18px;">explicit operator int() const;explicit opreator double() const;</span>


In short, C ++ provides the following type conversion for the class:

  • Only one parameter class constructor is used to convert the value of the same type as this parameter to the class type. For example, when an int value is assigned to a Stonewt object, the Stonewt class constructor that accepts the int parameter is automatically called. Explicit it can be used in the construction Declaration to prevent implicit conversion.
  • The special member operator function called a conversion function is used to convert a class object to another type. The conversion function is a class member and has no return value, no parameter, and is named operator typename (). If the class object is assigned to the typename variable or converted to the typename variable, the function is automatically called.

After learning so many types of knowledge, it is hard to digest for a moment. Here we may transfer it to the input and output of the file temporarily.

 

11.4 stream and Buffer

C ++ regards input and output as byte streams. During input, the program extracts bytes from the input stream; During output, the program inserts the bytes into the output stream. The bytes in the input stream may come from the keyboard or from the initial device or other programs. Similarly, the bytes in the output stream can flow to the screen, printer, storage device, or other devices. A stream acts as a bridge between a program and a worker or a stream target.

The input stream requires two connections, one for each end. The file end connection provides the stream source, and the program end connection dumps the output part of the stream to the program. Similarly, output management includes connecting the output stream to the program and associating the output target with the stream. Generally, you can use a buffer to process input and output more efficiently. A buffer is a memory block used as an intermediary. It is a temporary storage tool that transfers information from a device to a program or from a program to a device .. Generally, a device like disk memory has 512 bytes of block to transmit information, and a program can only process one byte of information at a time. The buffer method is to read a large amount of information from the disk, store the information in the buffer, and then read one byte each time from the buffer. This method is more efficient because data is read from memory than from disks.

The keyboard provides one character each time, so in this case, the program does not need a buffer to help match different data transmission efficiency. However, buffering the keyboard input allows the user to return and correct the input before it is transmitted to the program. C ++ usually refreshes the input buffer when you press Enter. This is why the program is processed when the user presses the carriage return. For screen output, the C ++ program usually refreshes the output buffer when the user sends a line break.

 

11.5 stream, buffer, and iostream files

Managing streams and buffers is a bit complicated. iostream Contains classes specially designed to manage streams and buffers.

  • The streambuf class provides memory for the buffer, and provides class methods for filling the buffer, accessing the buffer content, refreshing the buffer, and managing the buffer memory;
  • The ios_base class indicates half of the stream features, such as reading, binary, or text streams;
  • The ios class is based on the ios_base class, which includes a pointer member pointing to the streambuf object;
  • The ostream class is derived from the ios class and provides the output method;
  • The ostream class is derived from the ios class and provides the input method;
  • The iostream class is based on the istream and ostream classes, so it inherits the input and output methods.

Here we will introduce some details about iostream class library management:

  • The cin object corresponds to the standard input stream. By default, the stream is associated with a standard input device (keyboard). wcin and wcout are similar, but wchar_t type is used;
  • The cout object corresponds to the standard output stream. By default, the stream is associated with a standard output device (Display). The wcout object is similar, but the process is of the wchar_t type;
  • The cerr object corresponds to the standard error stream. By default, this stream is associated with a standard output device (Display ). This Liu is not buffered, which means that the information will be sent directly to the screen, instead of waiting until the buffer is filled or new line breaks. Werr sounds similar.
  • Clog objects also correspond to standard error streams. By default, the stream is associated with the standard output device (the reality server), and the stream is buffered. Wclog is similar to this.
  • An object represents a stream. What does this mean? When the iostream file declares a cout object for the program, the object will include data members that store the output-related information, for example, the field width, decimal places, counting method used for real data, and the address of the streambuf object used to process the buffer zone. The following statement is to put the characters in the string into the cout Management Buffer through the streambuf object.
<span style="font-size:18px;">cout<<"bju Masd";</span>

 


 

 

 

Today's status is not very good (probably because I want to go back to school today, and my heart is still inactive), so I wrote so much.


After reading c primer plus, what should I do?

I personally think it is really good to read the book c primer plus (fifth edition) and understand it. I suggest you take a look at the number c expert programming, which is a little difficult, next I will go back to the book "c defects and traps", which is entertaining and interesting. "c primer plus (fifth edition) "c and pointer" and "C Programming Language" I personally think these three books are of almost the same grade. You can just select one to have a look!

Redirection of c primer plus

You have not initialized fname, so fname may not have the string Terminator '\ 0 '.
Scanf is dangerous to input strings. It is best to use fgets for string input.
Here you should replace char fname [50]; with char fname [50] = {0 };
Replace scanf ("% s", fname); with fgets (fname, 49, stdin );
In this way, you do not need to use "test.txt" in fopen.
 

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.