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

g++ error message when signedness of int type doesn't match

本文关键字:g++ 错误 消息 不匹配 类型 符号 int      更新时间:2024-05-10

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

void f(int &x) { x = 1; }
int main(int, char **)
{
unsigned int x;
f(x);
return 0;
}

当然,这里的问题是f想要取一个有符号的int作为引用,而我正试图传递一个无符号的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&"的非常量左值引用转换为"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;
}

由于函数只接受int,因此在传递unsigned int时,此程序仍会给您一个错误。

不能将另一个数据类型的地址传递给函数。

在发送其地址之前,必须将指针类型转换为unsigned int

void f(int *x) { *x = 1; }
int main(int, char **)
{
unsigned int x;
f(reinterpret_cast<int *>(&x));
return 0;
}

void f(int &x) { x = 1; }
int main(int, char **)
{
unsigned int x;
f((int&)x);
return 0;
}