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