数据类型转换
目录
- 一 隐式类型转换
- 1.1 算数转换
- 1.2 赋值转换
- 1.3 输出转换
- 二 强制类型转换
- 2.1 直接使用数据类型
- 2.2 static_cast
- 2.3 dynamic_cast
- 2.4 const_cast
- 2.5 reinterpert_cast
一 隐式类型转换
1.1 算数转换
(+,-,*,/,%)
char , int, long, long long, float, double
15 + 3.14 => 15.0 + 3.14
1.2 赋值转换
#include
int main(void) {
int x;
// 计算结果31.4 转换为int类型,因为赋值符号的左边变量的类型是int类型
x = 3.14 * 10.0;
cout << x << endl; //31
return 0;
}
1.3 输出转换
#include
int main(void) {
printf("%c\n", 255+50); // 305(0001 0011 0001) -> 0x31(一个字节是8个位) -> 49 ('1');
printf("%d\n", 255+50); // 305
return 0;
}
二 强制类型转换
2.1 直接使用数据类型
int x = 257 + 100;
cout << "x=" << x << endl; // 357
x = (char)257 + 100; // 0001 0000 0001 -> 0000 0001
cout << "x=" << x << endl; // 101