C++学习笔记十:数据类型的转换

一个表达式里的所有变量应该具有相同的类型。

 

1.隐式转换(implicitly): 编译器自动进行。总是把占用内存小的数据类型转化为占用大的数据类型,或者是把signed(有符号的)转换为unsigned(无符号的)。

int类型转换为double

double price { 45.6 };
int units {10};
auto total_price = price * units; // units will be implicitly converted to double
std::cout << "Total price : " << total_price << std::endl;
std::cout << "sizeof total_price : " << sizeof(total_price) << std::endl;

int类型转换为unsigned int类型,赋负值后会存入垃圾值。

int a {20};
unsigned int b {23};
auto c = a + b;
c = -123;
std::cout << c << std::endl; //reuslt:4294967173

窄转换(narrow conversion): 不同变量类型的赋值会导致窄转换导致精度丢失。

int x;
double y {45.44};
x = y; // double to int
std::cout << "The value of x is : " << x << std::endl; // 45
std::cout << "sizeof x : " << sizeof(x) << std::endl;// 4

 

2.显式转换(explicit conversion)

static_cast<type>(Variable):编译器会检查转换是否兼容

double x { 12.5 };
double y { 34.6 };
int sum = x + y; 
std::cout << "The sum  is : " << sum << std::endl;
//Explicity cast : cast then sum up
sum = static_cast<int>(x) + static_cast<int>(y) ;
std::cout << "The sum  is : " << sum << std::endl; //46
//Explicit cast : sum up then cast, same thing as implicit cast
sum =  static_cast<int> (x + y); //47
std::cout << "Sum up then cast, result : " << sum << std::endl;

old style C-Cast: (type)(Variable)

//Old style C-cast
double PI {3.14};
//int int_pi = (int)(PI);
int int_pi = static_cast<int>(PI);
std::cout << "PI : " << PI << std::endl;
std::cout << "int_pi : " << int_pi << std::endl;

 

3.上溢和下溢(overflow and underflow)

比如unsigned char类型的大小是1 Byte, 它可以存储 0~255区间内的数值,如果赋值256导致上溢,赋值-1导致下溢。编译器有时会报warning错误,有时会存入垃圾值或者是出现不易察觉的错误。如果不确定数据类型的范围,建议使用<limits>库来查询。

unsigned char a {255};
a++;
std::cout << a << std::endl;

 

posted @ 2023-12-14 15:44  Sternenhimmel1997  阅读(77)  评论(0)    收藏  举报