(Struct *) 使用属性值名称初始化?
(Struct *) Initialization using attribute value name?
我已经定义了这个结构:
typedef struct WHEATHER_STRUCT
{
unsigned char packetID[1];
unsigned char packetSize[2];
unsigned char subPacketID[1];
unsigned char subPacketOffset[2];
...
} wheather_struct;
我如何通过属性名称来初始化这个结构(使用构造函数或 new)?例如:
wheather_struct.packetID = 1;
Finally
我试过这个解决方案,它对我有用,但你认为这是一个不错的选择吗?
WHEATHER_STRUCT * wheather_struct = new WHEATHER_STRUCT();
*weather_struct->packetID = '1';
对于浮动属性:
wheather_struct->floatAttribute= 111.111
在 C++ 中,您可以使用 new
分配和初始化:
wheather_struct *p = new wheather_struct();
注意末尾的括号 - 这是 value initialization - 用 0 填充内置类型的成员。
然后:
p->packetID[0] = 1;
您可以将初始化器 {}
添加到您的数组以将它们初始化为零,如下所示:
struct wheather_struct // no need for typedef in C++
{
unsigned char packetID[1]{};
unsigned char packetSize[2]{};
unsigned char subPacketID[1]{};
unsigned char subPacketOffset[2]{};
};
然后使用new
动态创建对象:
auto w = new weather_struct;
w->packetID[0] = 'A';
以后别忘了删除:
delete w;
但是(更好)使用智能指针:
auto w = std::make_unique<weather_struct>(); // will delete itself
w->packetID[0] = 'A';
// no need to delete it
或者(甚至更好)将其用作值对象(并非总是可能):
weather_struct w;
w.packetID[0] = 'A';
我已经定义了这个结构:
typedef struct WHEATHER_STRUCT
{
unsigned char packetID[1];
unsigned char packetSize[2];
unsigned char subPacketID[1];
unsigned char subPacketOffset[2];
...
} wheather_struct;
我如何通过属性名称来初始化这个结构(使用构造函数或 new)?例如:
wheather_struct.packetID = 1;
Finally
我试过这个解决方案,它对我有用,但你认为这是一个不错的选择吗?
WHEATHER_STRUCT * wheather_struct = new WHEATHER_STRUCT();
*weather_struct->packetID = '1';
对于浮动属性:
wheather_struct->floatAttribute= 111.111
在 C++ 中,您可以使用 new
分配和初始化:
wheather_struct *p = new wheather_struct();
注意末尾的括号 - 这是 value initialization - 用 0 填充内置类型的成员。
然后:
p->packetID[0] = 1;
您可以将初始化器 {}
添加到您的数组以将它们初始化为零,如下所示:
struct wheather_struct // no need for typedef in C++
{
unsigned char packetID[1]{};
unsigned char packetSize[2]{};
unsigned char subPacketID[1]{};
unsigned char subPacketOffset[2]{};
};
然后使用new
动态创建对象:
auto w = new weather_struct;
w->packetID[0] = 'A';
以后别忘了删除:
delete w;
但是(更好)使用智能指针:
auto w = std::make_unique<weather_struct>(); // will delete itself
w->packetID[0] = 'A';
// no need to delete it
或者(甚至更好)将其用作值对象(并非总是可能):
weather_struct w;
w.packetID[0] = 'A';