【问题标题】:g++ error message when signedness of int type doesn't match当 int 类型的符号不匹配时的 g++ 错误消息
【发布时间】: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&amp;, can only refer to an "lvalue," which is a named variable. 在您的情况下,要么将两个声明都更改为“int”,要么将两者都更改为“unsigned int”。
  • @paulsm4:不。我的问题不是关于如何修复程序,我的问题是关于错误消息。

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


【解决方案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++,不是 C。你可以传递引用。
【解决方案2】:

您不能将其他数据类型的地址传递给函数。

在发送地址之前,必须将指针类型转换为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;
}

【讨论】:

  • 我的问题不是关于如何修复程序,我的问题是关于错误消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 2014-05-01
相关资源
最近更新 更多