There are rich types in C + + that require type conversions when operating on different types.
General conversion Rules: convert small-range types to large-range types, such as: Float->double,short->int,int->long, and so on. C + + is converted so as not to lose precision, but for applications with high data accuracy, the loss of precision is undoubtedly a disaster. It should be noted that when you assign 0 to a bool variable, it is converted to false, and not the 0 value is converted to true.
Transformations in an expression:
When two different arithmetic types are included in the same expression, C + + performs two kinds of automatic conversions. 1. Some types will be converted automatically when they appear; 2. Some types are converted when other types are present in an expression.
Automatic conversion: C + + converts the bool,char,unsigned char,signed char,short value to int when evaluating an expression. This conversion becomes a cosmetic lift (integral promotion). Example: When two short variables are added, C + + converts the short type to int, which is added and then converted to the type of the left operand of the assignment number. As for the 2 follow the conversion rules can not repeat.
Forced type conversions
There are two types of forced type conversion formats: 1, (TypeName) value;2, TypeName (value)
The first form is derived from the C language. The second format is C + + specific, like a function call!
In addition, C + + introduced 4 mandatory type conversion budget, discussed later. The following code is given:
Type conversions
#include <iostream>
int main ()
{
using namespace Std;
int intthree = 3; The small range value is paid to a large range of values without loss of precision. Conversely, it is possible to lose precision, which can cause trouble.
Long lthree = Intthree;
cout<<lthree<<endl; Output:3
Long lnum = 3456765;
Short snum = Lnum;
cout<<snum<<endl; Output: 16643
cout<<lnum<<endl; output:3456765
Signed int intfu =-5;
unsigned int intzheng = 10000;
cout<<intfu<<endl; Output: 5
int inth = 64;
Forcing a type conversion does not change the value of the variable itself, but instead creates a new, specified type in the value that is typically used in an expression.
cout<<static_cast<unsigned char> (inth) <<endl; Output: @
}
C + + type conversions