C++ 重载与有符号和无符号 int 不同

标签 c++

使用重载函数定义编译 C++ 时,为什么有符号和无符号整数类型的提升行为不同?这是预期的行为吗?

在下面的示例中,main 中对“fail”的调用是模棱两可的,但对“pass”的调用不是。

unsigned int fail(unsigned int a) {
  return a;
}

unsigned int fail(unsigned short a) {
  return a;
}

int pass(int a) {
  return a;
}

int pass(short a) {
  return a;
}


int main(){

  unsigned char a;
  char b;
  fail(a);
  pass(b);

  return 0;
}

示例输出(来自 clang,VS 编译器给出了类似的内容):

fail.cpp:22:3: error: call to 'fail' is ambiguous
  fail(a);
  ^~~~
fail.cpp:1:14: note: candidate function
unsigned int fail(unsigned int a) {
             ^
fail.cpp:5:14: note: candidate function
unsigned int fail(unsigned short a) {
             ^
1 error generated.

最佳答案

根据integral promotion (强调我的):

The following implicit conversions are classified as integral promotions:

  • signed char [...] can be converted to int;
  • unsigned char [...] can be converted to int if it can hold its entire value range, and unsigned int otherwise;
  • char can be converted to int or unsigned int depending on the underlying type: signed char or unsigned char (see above);

Note that all other conversions are not promotions; for example, overload resolution chooses char -> int (promotion) over char -> short (conversion).

在您的情况下,鉴于 int 能够同时保存 signed charunsigned char 的整个值范围,只有 >int pass(int a)是一种提升,比剩下的三个转化更可取,转化之间没有偏好。

关于C++ 重载与有符号和无符号 int 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49817416/

相关文章:

c++ - 使用不同功能的队列中的打印元素不会在_start程序中全局清空队列。还有更多解释吗?

c++ - 使用 clang Libtooling API 打印完全限定类型的参数 (ParmVarDecl) 或字段 (FieldDecl)

c++ - 是否可以在编译时获取时间(当天)和日期?

c++ - 是否可以同时用两个程序写入和读取文本文件

c++ - 静态常量类成员

c++ - std::move 内部 move 赋值运算符

c++ - 特征向量数组的 vector 运算

c++ - 如何检查正则表达式是否陷入无限循环?

c# - 在 c# 中等效于 'Base64' 在 c 编程中生成的加密字节的编码字符串将在 URL 查询字符串中发送

c++ - 如何将 C++ STD 与 AVR 编译器一起使用?