[英]Assign enum member to void pointer?
I have a void pointer that has to hold some information and there I wanted to assign it to a int based on my enumeration. 我有一个void指针,必须保存一些信息,我想根据我的枚举将它分配给一个int。 I want this integer to be available through all the time so that the void pointer isn't pointing to "garbage".
我希望这个整数一直可用,以便void指针不指向“垃圾”。 Here is the code:
这是代码:
enum type {nc, ns, nd};
void* thatType;
thatType = &nc
The outcome of this, is that I get this error: expression must be an lvalue or a function designator So is "nc" an actual variable or does it just work like a placeholder for the integer of 0? 结果是,我得到了这个错误:表达式必须是左值或函数指示符因此,“nc”是一个实际变量,还是像占位符一样工作为0的整数? If I then did this:
如果我那么这样做:
thatType = (int*)nc
First of all, why does this not give me an error then? 首先,为什么这不会给我一个错误呢?
Those are two very different things. 这是两件截然不同的事情。
&nc
This is trying to take the address of an enumerator, but enumerators aren't objects and don't have addresses. 这是尝试获取枚举器的地址,但枚举器不是对象,也没有地址。 It's like trying to write
&42
to get the address of the literal 42
. 这就像尝试写
&42
来获取文字42
的地址。 Only string literals have addresses (more or less). 只有字符串文字才有地址(或多或少)。
(int*)nc
This, on the other hand, is taking the integer value of nc
(which is 0
) and converting it to a pointer. 另一方面,这是取
nc
的整数值(即0
)并将其转换为指针。 Basically you're writing (int*)nullptr
. 基本上你在写
(int*)nullptr
。 That's legal, though questionable (which is why, of the C++ casts, only a reinterpret_cast
will compile here). 这是合法的,虽然有问题(这就是为什么,在C ++演员表中,只有
reinterpret_cast
会在这里编译)。
Notice in particular that you did not write (int*)&nc
. 特别注意你没有写
(int*)&nc
。
does it just work like a placeholder for the integer of 0?
它只是像占位符一样工作0的整数?
Basically, yes, that's right. 基本上,是的,那是对的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.