C++_ series of self-study Courses _ _11_ Class _ Type Conversion _ C + + Primer fourth Edition

Source: Internet
Author: User
Tags true true

Last time I said something about the expression, and there are some things about data type conversions, today we go on to 818 data type conversions in C + +.

One, implicit type conversion

In expressions, some operators can manipulate multiple types of operands, for example, the + operator can have either an int or float type, which introduces the question of what

The type that determines the value of an expression. For example:

  3.1415926 5;   // double type  + integer, result why type??  3.14159262  *  3//Double type * integral type  * integer; What is the value of the resulting expression??  24UL;   // integer * Unsigned integer  , what is the type of the value of the resulting expression??     

In C + +, the mechanism of type conversion is introduced in order to solve this kind of problem.

  

1. When will a type conversion occur?

A: In an expression with a mixed type, a type conversion occurs, as in the example above.

3.14 * 4; Type conversions occur at the time of calculation, converting 4 to 4.0 and multiplying by 3.14.

B: An expression used as a condition is converted to type bool

    int      IVar; ... .. if (IVar) ....

A type conversion occurs here as a conditional expression of the IF statement, and when the IVar nonzero is converted to true, the IVar is converted to false when the IVar is 0 o'clock.

C: When a variable of type bool, value is not! , &&, | | A type conversion occurs when the operand of an operator

    BOOL      Bvar; ... .. int      IVar;  int= IVar + Bvar;  //

As shown above, the bool amount Bvar will occur type conversion, when Bvar is true true when converted to 1, when false false Bvar will convert 0, so that you can participate in the calculation.

D: Type conversion occurs when the left and right operands of the assignment operator are of inconsistent type

    int   =3.1415926//Double type 3.1415926 is converted to int type assignment to Ivar;

Here, the value of the double type is converted to the int type.

E: Type conversions occur when other types of values initialize variables

  int  3.1415926;  // Assignment Initialization,
Or
  int IVar (3.1415926); // Direct Initialization

When initialized here, the 3.1415926 is converted to int, and then the Ivar is initialized.

2. Arithmetic conversion

C + + provides a set of default data type conversion mechanisms for built-in operators and data types, the most common of which is arithmetic conversions. Arithmetic operator + 、-、 *,/two operand types are inconsistent

Data type conversions occur, and before the program executes, the operands on either side of the arithmetic operator are converted to the same data type before the arithmetic operation is performed. The basic principle of arithmetic conversion is to guarantee the calculation after the conversion.

Precision. For example, if the operand of an arithmetic operator has a long double then the other operand is converted to a long double type and then evaluated.

In C, there are the following basic types of conversion features:

Note that the float type is not automatically converted to a double type, which requires special attention. in C + +, the general principle of such a translation is maintained, we can look at the results of the operation using the sizeof operator.

Exp:

intMain () {cout<<"sizeof (3.14L * 2) is:"<<sizeof(3.14L*2) <<Endl; cout<<"sizeof (3.14 * 2) is:"<<sizeof(3.14*2) <<Endl; cout<<"sizeof (3.14F * 2) is:"<<sizeof(3.14f*2) <<Endl; cout<<Endl; cout<<"sizeof (long int) is"<<sizeof(Long int) <<Endl; cout<<"sizeof (' a ' * ' a ') is:"<<sizeof('a'*'a') <<Endl; cout<<"sizeof (2L * 2) is:"<<sizeof(2L*2) <<Endl; return 0;}

The execution result of the program is:

[Email protected] cpp_src]# g++test.cpp [[email protected] cpp_src]#./A. out sizeof(3.14L*2) is: Asizeof(3.14*2) is:8sizeof(3.14f*2) is:4sizeof(Long int) Is4sizeof('a'*'a') is:4sizeof(2L*2) is:4

A summary sentence is:

    1, for all types smaller than the int type, in the process of calculation will be converted to int, if its value is contained within an int, the operand will be converted to int and then evaluated if its value

more than an int is converted to the unsigned int type for calculation. If there is a long type in the operand, it is converted to a long type for evaluation.

2, for floating-point type, if there is a long double is converted to a long double for the calculation, if there is a double type, it will be converted to a double type for calculation, if there is a float

will be converted to The float type is calculated.

It is important to note that the float type is not automatically promoted to a double type, which is not the same as the integral type.

3, about the conversion between signed and unsigned numbers

The discussion is about the unsigned number of integers and the direct conversion of signed numbers, which is one of the most difficult points in the C + + language, which I have discussed earlier in this article. Here again to describe again.

A: Two operands of unsigned short int and int

If int is sufficient to hold the value of the unsigned short int, the int is converted for evaluation, and if it cannot be saved, it is converted to unsigned int for calculation.

B: Two operands of unsigned int and long int

If long int is sufficient to hold all the values of the unsigned int type, it is converted to a long int for evaluation, otherwise it is converted to unsigned long int.

C: two operands of int and unsigned int

This place is a little bit to note that int is converted to unsigned int after the calculation, the result of the calculation is unsigned int type, and then if assigned to the int type, then overflow may occur

, the value of the unsigned int type is assigned to the int type by truncating the high-level section.

This place generally does not require special attention, but in some special places there is a need for special attention.

4. About pointers and arrays

This problem was described in one of my previous essays, which is that in general, arrays (names) can be converted to pointers. For example:

  int    iarray[3];  int   *pint = IArray;   The array (first name) is converted to a pointer type, and then the pointer variable is initialized pint

This conversion is based on the idea that the array name is the first address of an array, and is a constant, immutable, and cannot be assigned to a group name.

Points:

1, sizeof (IArray); This place does not convert the array name to a pointer.

2. When a reference is defined, the array name is not converted to a pointer

Exp:

int Main () {    int iarray[5] = {1,2,3,4,5 };     int (& Refarray) [5] = IArray;    cout<<"iarray[0]="<<refarray[0]<<Endl ;     return 0 ;}

The results of the execution of the program are as follows:

[Email protected] cpp_src]# g++ test.cpp [[email protected] cpp_src]#. /a . Out iarray[0]=1

5, about the conversion rules of type bool

Other non-bool type built-in types if you are converting to a bool value, a non-0 conversion is true, and 0 is converted to false false.

type bool converts int, true to 1, false to 0

6. Enum type conversion rules

An enumeration type is a custom data type that is defined by the keyword enum. Enumeration types are often used to define properties or states, such as defining some values for the week, and defining some values that represent the file's

Open, close states, define some values to indicate busy, busy, and so on.

A: Defining enum types

Syntax: Enum enum type name {enum type can take value};

Exp:

  enum   Open_mode  {input, output, append}  //  defines the enumeration type Week, the variable of this type can take the value: input, output, append   enum    Open_mode  status = input;  // defines the enumeration type variable status and initializes it to input

Note that when you define a variable of an enumeration type, the keyword enum cannot be omitted unless the alias is defined with a typedef for the enumeration type.

B: Enumeration Type value

By default, when an enumeration type is defined, its first value defaults to 0, and the value of the subsequent value increases by 1 by default.

For example:

Enum File_status {close, open}; The value of the default close here is 0, and the value of open is 1

You can also specify these values,

For example:

Enum File_status {close = ten, open}; Here close = 10, while Open has a value of 11

  

Points:

You can have two values equal when specifying the value of an enumeration.

  enum  2 , point2w, Point3D 3,   point3w};  // This requires attention, but generally does not define the enumeration data type

C: Conversion rules for enum types

An enumeration type can participate in a calculation, and its value can be converted to the value of type int, its converted value, determined by the value of the enumeration type.

enum Open_mode  {input, output,append}    = input;  intten + EVar;  // The Evar is converted to the value 0 of the int type, and then the value of the expression is evaluated

Second, display type conversion

The display type conversion is a clear indication of the type conversion rule in the program, which overrides the system's default implicit conversion rules. Implicit conversions are: dynamic_cast, static_cast, Const_cast,

Reinterpret_cast.

1, dynamic_cast

Support run-time identification pointers or reference execution objects, to be followed by special essays to be introduced.

2, Const_cast

Const_cast is to force the Const property of the const object to be canceled so that we can display the value of the modified object. Here is not clear, do not know which big God, to understand here more thorough, please

Feel free

3, static_cast

Static_cast is the same as forcing type conversions in the C language, except that the method is different. Of course, C + + also supports the forced type conversion of language style.

  Char  Chvar = static_cast<char> (1234);  // The display converts 1234 to a char type. 

Note here that the static_cast is followed by the data type that <> is going to convert to, and the operand to be converted by the () operator.

Mandatory type conversions for C-language styles:

  char Chvar = (char)1234;

There is not much discussion here.

4, Reinterpret_cast

Reinterpret_cast usually provides a mechanism for the re-interpretation of the bitwise patterns of the operands.

For example:

  int    IVar;   int *pint = &IVar;   12345;  char *pch = reinterpret_cast<char *> (PINT);

Here, if we access the memory through a PCH, the system interprets the memory 4 bytes (32bit system) of the variable Ivar as a char array; it is noteworthy that Ivar and *pint access

This area of memory will still be interpreted as an int, which means that the mandatory reinterpret_cast does not change the data type that the original pointer points to or the data type of the original variable. This is especially necessary.

Attention.

About the type conversion for the time being so much content, other content to be continued ....

C++_ series of self-study Courses _ _11_ Class _ Type Conversion _ C + + Primer fourth Edition

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.