【发布时间】:2014-05-17 23:40:08
【问题描述】:
在 C++ 中,由于隐式类型转换,可以将 int 与 char 进行比较吗?还是我误解了这个概念?
例如,我可以做吗
int x = 68;
char y;
std::cin >> y;
//Assuming that the user inputs 'Z';
if(x < y)
{
cout << "Your input is larger than x";
}
或者我们需要先将其转换为 int 吗?
所以
if(x < static_cast<int>(y))
{
cout << "Your input is larger than x";
}
【问题讨论】:
-
请注意,
sizeof(int) == 1和char是无符号的是允许的,在这种情况下双方都将转换为unsigned int。不过,这很不寻常。 -
请避免使用幻数,写出你的意思:不是 68,而是
'D'。此外,即使sizeof(int)>1,也要注意实现定义的char签名。
标签: c++ types casting char int