【发布时间】: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 &seed 参数设为const 变量,因为我在函数中更改了它的值。提前致谢!
【问题讨论】:
-
转换后,你不再有左值了。您不能非 const 引用强制转换的值。首先定义一个
unsigned int变量。 -
不要使用 C 风格的强制转换,它们用于遗留代码。
标签: c++ arguments parameter-passing unsigned-integer