不能使用parameter作为无符号整型,通过引用传递

Cannot use parameter as an unsigned int with pass by reference C++

本文关键字:引用 整型 无符号 parameter 不能      更新时间:2023-10-16

我有一些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转换为参数的无符号int。我不能使unsigned int &seed参数成为const变量,因为我在函数中改变了它的值。提前感谢!

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

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

派生类型:

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

就是这样。您正在尝试用int初始化unsigned int&。或者,使用强制转换时,尝试用临时变量初始化左值引用。它们不符合两种允许的情况。你只需要传入正确的类型:

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

虽然,为什么random()改变种子?似乎你应该按值传递它…