为什么 cout 在与三元和 int 一起使用时打印 char 的 ascii 值?
Why does cout print the ascii value of a char when used with a ternary and int?
为什么此代码生成 42012 而不是 *012?我可以看到它正在将星号转换为其 ASCII 值,但为什么呢?
vector<int> numbers = {-1,0,1,2};
for(int num: numbers){
cout << (num == -1 ? '*' : num); //42012
}
for(int num: numbers){
if(num == -1) cout << '*'; //*012
else cout << num;
}
如果我使用普通的 if else 语句,它就可以工作。为什么?
三元表达式returns其真部分和假部分"common type",char
和int
之间的共同类型是int
,所以 '*'
被提升为 int
.
在上面找到了极客对极客的文章here
为什么此代码生成 42012 而不是 *012?我可以看到它正在将星号转换为其 ASCII 值,但为什么呢?
vector<int> numbers = {-1,0,1,2};
for(int num: numbers){
cout << (num == -1 ? '*' : num); //42012
}
for(int num: numbers){
if(num == -1) cout << '*'; //*012
else cout << num;
}
如果我使用普通的 if else 语句,它就可以工作。为什么?
三元表达式returns其真部分和假部分"common type",char
和int
之间的共同类型是int
,所以 '*'
被提升为 int
.
在上面找到了极客对极客的文章here