标准数据类型之间会进行隐式类型转换
转换规则如下:(小范围转换为大范围)
下面通过一段代码来说明隐式类型转换的危害:
#include <iostream>
#include <string>
using namespace std;
int main()
{
short s = 'c';
unsigned int ui = 1000;
int i = -2000;
double d = i;
cout << "d = " << d << endl;
cout << "ui = " << ui << endl;
cout << "ui + i = " << ui + i << endl; // 1.打印什么结果
if( (ui + i) > 0 ) // 2. 此处会走哪个分支
{
cout << "Positive" << endl;
}
else
{
cout << "Negative" << endl;
}
cout << "sizeof(s + 'b') = " << sizeof(s + 'b') << endl; // 3.该值为多少
return 0;
}
程序运行结果如下:
1. cout << "ui + i = " << ui + i << endl; // 1.打印什么结果 发现并没有打印 我们期望的 -1000 而是一个超级大数,为什么?
这就是因为发生了隐式类型转换的原因 ,通过转换表得知 unsinged int + int 会先见 int 隐式转换为 unsigned int 然后在进行加法运算 故会出现 如上结果 一个很大的数,而不是 -1000 故 2 会走 cout << "Positive" << endl; 这条语句
3. cout << "sizeof(s + 'b') = " << sizeof(s + 'b') << endl; // 3.该值为多少 short + char 不是我们猜想的 最后为short 通过转换表得知 先将short 转换为 int 在将 char 转换为int 然后进行相加操作 ,故最后结果为 int 故会看到上面打印的 4 故在工程中尽量避免隐式类型转换