【发布时间】:2021-01-14 07:13:55
【问题描述】:
如果我只是从一个示例程序开始,这是最简单的。 (注意:我的问题不是关于如何修复此程序的问题。如果您的回答只是关于如何修复此程序而不是关于我的问题,请不要回复。)
void f(int &x) { x = 1; }
int main(int, char **)
{
unsigned int x;
f(x);
return 0;
}
当然,这里的问题是 f 想要将 signed 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&' 类型的非常量左值引用绑定到 'int' 类型的右值”
我最好的猜测是它试图将 unsigned int 类型的左值隐式转换为 int 类型的右值,然后卡住了。但是为什么它会在这次尝试中途报告结果呢?还有为什么这里不报告类型unsigned intanywhere?
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; }
问题:这是怎么回事?我假设编译器必须尝试转换以查看它是否有帮助和失败,但是在此过程中途发出错误消息并且不会引用原始类型是没有意义的。
【问题讨论】:
-
也许 GCC 试图将
main变量x转换为int,但它确实是一个不能绑定到非 const 左值引用的右值,因此错误。 -
您使用的是哪个版本的 GCC?您是否尝试过其他版本(例如 the compiler explorer)?
-
@Someprogrammerdude:看起来在 gcc 5 之前它实际上给出了更有用的信息。
-
这能回答你的问题吗? Error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’。具体来说:
A non-const reference parameter, such as an int&, can only refer to an "lvalue," which is a named variable.在您的情况下,要么将两个声明都更改为“int”,要么将两者都更改为“unsigned int”。 -
@paulsm4:不。我的问题不是关于如何修复程序,我的问题是关于错误消息。
标签: c++ gcc compiler-errors g++ type-promotion