[英]Accessing union elements in C++
I have been implementing a communication protocol in C++ and I have decided to model one packet in below given manner. 我一直在用C ++实现通信协议,我决定以下面给定的方式对一个数据包建模。
union control_pkt_u{
struct pkt_parts_t{
uint8_t header[3]; // Control packet header
uint8_t payload[NO_PYLD_BYTES_IN_CONTROL_PACKET]; // Control packet payload
};
uint8_t pkt_array[NO_BYTES_IN_PACKET];
};
As soon as I need to access to the elements of the union 一旦我需要访问工会的要素
pkt.pkt_parts_t.header[0] = APP_MSG_DEB;
I receive an error during compilation: 编译期间收到错误消息:
invalid use of struct Manager::control_pkt_u::pkt_parts_t
Please can anybody tell me what I am doing wrong? 请有人能告诉我我在做什么错吗?
Because you are just defining a struct in your control_pkt_u
union and it is just a declaration, it is not initialised when you create an object from it. 因为您只是在
control_pkt_u
联合中定义了一个结构,并且它只是一个声明,所以在从该对象创建对象时不会对其进行初始化。 You need to declare it as a member like this and reach your member pkt_parts_
. 您需要将其声明为这样的成员,并到达您的成员
pkt_parts_
。
union control_pkt_u {
struct pkt_parts_t {
uint8_t header[3]; // Control packet header
uint8_t payload[NO_PYLD_BYTES_IN_CONTROL_PACKET]; // Control packet payload
} pkt_parts_;
uint8_t pkt_array[NO_BYTES_IN_PACKET];
};
pkt.pkt_parts_.header[0] = APP_MSG_DEB;
You can change the struct definiation to this by using Anonymous structure : 您可以使用匿名结构将结构定义更改为:
struct {
uint8_t header[3]; // Control packet header
uint8_t payload[NO_PYLD_BYTES_IN_CONTROL_PACKET]; // Control packet payload
} pkt_parts_t;
Then you don't need to change other code. 然后,您无需更改其他代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.