不能使用parameter作为无符号整型,通过引用传递
Cannot use parameter as an unsigned int with pass by reference C++
我有一些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()
改变种子?似乎你应该按值传递它…
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- JNI 日期值转换问题,在C++中获取不同的长整型值
- 将长整型值打印为带有前导零的十六进制
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 将整型常量映射到类型
- 将元组和整型实例合并到引用元组中
- 提升不良词法强制转换:将字符串转换为无符号长整型时,无法将源类型值解释为目标
- 为什么C++不允许两个同名的函数/类模板,区别仅在于非类型模板参数(整型)的类型?
- 将最小值整数转换为无符号长整型
- 如何将小端格式的QByteArray转换为无符号长整型
- 直接初始化无符号短整型的标准行为
- 类型为"短整型 (&)"的引用初始化无效
- 在 c++ 对象上使用 extern 时未定义引用,但不是整型
- 不能使用parameter作为无符号整型,通过引用传递
- 需要const引用的函数的整型输入
- 引用整型数组的指针
- 通过引用传递指向长整型指针
- 作为唯一类成员的引用为整型提供大小为8的值