c++ - 当 int 类型的符号不匹配时的 g++ 错误消息

标签 c++ gcc compiler-errors g++ type-promotion

如果我只是从一个示例程序开始,这是最简单的。 ( 注意 :我的问题不是关于如何修复这个程序。如果你的答案只是关于如何修复这个程序而不是关于我的问题,请不要回复。)

void f(int &x) { x = 1; }

int main(int, char **)
{
  unsigned int x;

  f(x);

  return 0;
}
当然这里的问题是f想要将带符号的 int 作为引用,而我试图将其传递给 unsigned int。
但是,来自 g++ 的编译器警告令人费解:
<source>: In function 'int main(int, char**)':

<source>:7:5: error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'

    7 |   f(x);

      |     ^

<source>:1:13: note:   initializing argument 1 of 'void f(int&)'

    1 | void f(int &x) { x = 1; }

      |        ~~~~~^
如果它超出屏幕的一侧并且您不想滚动,则错误消息是“无法将'int&'类型的非常量左值引用绑定(bind)到'int'类型的右值”
我最好的猜测是它试图将 unsigned int 类型的左值隐式转换为 int 类型的右值,然后卡住了。但是为什么它会在这次尝试中途报告结果呢?以及为什么不报告类型unsigned int这里的任何地方?
clang 明显更有帮助:
<source>:7:3: error: no matching function for call to 'f'

  f(x);

  ^

<source>:1:6: note: candidate function not viable: no known conversion from 'unsigned int' to 'int &' for 1st argument

void f(int &x) { x = 1; }
问题:这里发生了什么?我假设编译器必须尝试转换以查看它是否有帮助和失败,但是在此过程中途发出错误消息并且不会引用原始类型是没有意义的。

最佳答案

您必须传递 unsigned int 的地址到function .

void f(int *x) { *x = 1; }

int main(int, char **)
{
  unsigned int x;

  f(&x);

  return 0;
}
当你传递 unsigned int 时,这个程序仍然会给你一个错误。因为该函数只接受 int .

关于c++ - 当 int 类型的符号不匹配时的 g++ 错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64106672/

相关文章:

c++ - 使用嵌套类函数时非静态数据成员的使用无效,但是当函数未嵌套时可以吗?

C++:为什么 int array[size] 有效?

c - 如果我不小心在 ARM 上运行 x86 二进制文件,如何显示错误消息?

java - 类型为Printwriter的方法println(boolean)不适用于参数(void)

compiler-errors - 在LAN中运行MPI群集程序时出错

c++ - 具有两个目标和两种语言的 Makefile

c++ - Qt 应用程序在随机时间后在 meego 上拉伸(stretch)

c - C、C99、ANSI C 和 GNU C 之间有什么区别?

32位编译报错

grails - STS IDE下划线域字段