错误:左值要求为一元&操作数 [英] error: lvalue required as unary & operand
问题描述
在编译时(使用Linux Server 6.1版)
While compiling (with Linux Server release 6.1)
strftime(AppTime, sizeof(AppTime),"%Y/%m/%d %T", localtime(&((long)u32_Time)));
获取错误错误:必须为一元'&'的左值操作数"
getting error "error: lvalue required as unary '&' operand"
,但相同的代码已在Red Hat Enterprise Linux AS发行版3中成功编译.
but the same code compiled successfully with Red Hat Enterprise Linux AS release 3.
为什么呢?该如何纠正?
Why so? How to correct this?
推荐答案
地址操作符&
需要一个变量来获取地址.强制转换(long)u32_Time
的结果是临时的,不一定驻留在内存中,因此没有可以使用的地址.因此,如果那段代码曾经在某个地方编译过,那么它就是一个非标准的编译器扩展.
The address-operator &
requires a variable to take the address from. The result of your cast (long)u32_Time
is a temporary that does not necessarily reside in memory and therefore has no address that could be taken. So if that piece of code ever compiled somewhere it was a nonstandard compiler extension.
该标准§5.3.1,3要求:
The standard, §5.3.1,3 demands:
一元&的结果运算符是指向其操作数的指针.操作数应为左值[...]
The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue [...]
如何解决此问题: std :: localtime
需要一个指向 std :: time_t
的指针,因此您最好提供它.您没有提供任何解释或进一步的代码,因此我只能猜测 u32_Time
是某种4字节无符号算术类型,应该以某种方式表示时间.如何将其正确转换为 std :: time_t
取决于您的编译器如何实现后者以及如何获得进一步的价值.简单地应用C-cast是 not 可移植的,而强制转换为 long
则更不易移植.
当且仅当当前平台上的 std :: time_t
也是无符号的32位类型,并且使用与相同的表示形式> u32_Time
,使用
How to fix this:
std::localtime
expects a pointer to a std::time_t
so you best provide that. You did not provide any explanation or further code, so I can only guess that u32_Time
is some 4 byte unsigned arithmetic type that is supposed to represent a time in some manner. How that is properly converted into a std::time_t
depends on how your compiler implements the latter and how you got the value of the further. Simply applying a C-cast is not portable, and casting to long
is even less portable.
If, and only if the std::time_t
on your current platform is also a unsigned 32 bit type using the same representation as your u32_Time
, it might suffice to use
localtime(reinterpret_cast<std::time_t*>(&u32_Time));
更多可移植的设备会首先将值存储在正确的数据类型中:
More portable would be storing the value in the correct data type first:
std::time_t time = u32_Time;
localtime(&time);
这样,如果 time_t
和 u32_Time
的类型不兼容,您将得到必要的警告和/或错误.
That way you will get the necessary warnings and/or errors if time_t
and the type of u32_Time
are not compatible.
我强烈建议您不要使用C-cast,因为一旦您不得不将这段代码移植到另一个平台上,您将无法轻松找到这种讨厌的演员.
I would strongly advice against using C-casts, because once you have to port this piece of code to another platform you will have no means to find that nasty cast easily.
这篇关于错误:左值要求为一元&操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!