【问题标题】:Cannot use parameter as an unsigned int with pass by reference C++不能将参数用作 unsigned int 并通过引用传递 C++
【发布时间】:2015-12-24 09:06:48
【问题描述】:

我有一些 C++ 代码:

#include <bjarne/std_lib_facilities.h>

double random(unsigned int &seed);
int main ()
{
    int seed = 42;
    cout << random((unsigned int)seed) << endl;
}

double random(unsigned int &seed)
{
    const int MODULUS = 15749;
    const int MULTIPLIER = 69069;
    const int INCREMENT = 1;
    seed = (( MULTIPLIER * seed) + INCREMENT) % MODULUS;
    return double (seed)/MODULUS;
}

我在尝试编译时遇到错误:

error: invalid initialization of non-const reference of type ‘unsigned int&’ from an rvalue of type ‘unsigned int’

cout << random((unsigned int)seed) << endl;

我不明白为什么我不能使用int seed 作为函数random 的参数。我什至尝试将type-casting int 转换为参数的无符号整数。我无法将unsigned int &amp;seed 参数设为const 变量,因为我在函数中更改了它的值。提前致谢!

【问题讨论】:

  • 转换后,你不再有左值了。您不能非 const 引用强制转换的值。首先定义一个unsigned int 变量。
  • 不要使用 C 风格的强制转换,它们用于遗留代码。

标签: c++ arguments parameter-passing unsigned-integer


【解决方案1】:

当你有一个类型的左值引用时,你只能用那个类型的东西来初始化它

T obj = ...;
T& ref = obj;

派生类型

Derived obj = ...;
Base& ref = obj;

就是这样。您正在尝试使用int 初始化unsigned int&amp;。或者,通过强制转换,您正在尝试使用临时初始化左值引用。这些都不符合两种允许的情况。您只需传入正确的类型即可:

unsigned int seed = 42;
cout << random(seed);

虽然,为什么random() 会改变种子?看来您应该按值传递它...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    相关资源
    最近更新 更多