考虑这个程序:
#include <iostream>
using namespace std;
void f(unsigned char c) {
cout << c << endl;
}
void f(int c) {
cout << c << endl;
}
int main() {
f('a');
}
这会打印出 97
,表明选择的 f()
重载是采用 int
的重载。我觉得这很奇怪;直觉上 unsigned char
不是更适合 char
吗?
最佳答案
wouldn't intuitively an
unsigned char
be a better match for achar
?
嗯,我想,但不是根据标准。根据 [conv.prom]p1
:
A prvalue of an integer type other than
bool
,char16_t
,char32_t
, orwchar_t
whose integer conversion rank is less than the rank of int can be converted to a prvalue of typeint
ifint
can represent all the values of the source type; [...]
现在,这三种字符类型具有相同的等级,而有符号类型的等级总是小于int
。 .这是 [conv.rank]p1.6
的组合和 [conv.rank]p1.2
:
The rank of a signed integer type shall be greater than the rank of any signed integer type with a smaller size.
[...]
The rank of
char
shall equal the rank ofsigned char
andunsigned char
.
基本上,每个字符的等级总是小于 int
它们都可以用 int
表示,因此 unsigned char
的过载不是更好的匹配,因为它会涉及从 char
的转换至 unsigned char
,而不是促销。
如果您将重载更改为 char
,那么就会有一个完全匹配,因此自然会选择“正确的”重载(在您看来)。
关于c++ - 为什么采用 int 的函数重载优于采用 unsigned char 的函数重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45775764/