gpt4 book ai didi

c++ - 在单个结构中处理不同的数据类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:27 26 4
gpt4 key购买 nike

我需要在 VxWorks 消息队列上发送一些信息。要发送的信息是在运行时决定的,可能是不同的数据类型。我为此使用了一个结构 -

struct structData
{
char m_chType; // variable to indicate the data type - long, float or string
long m_lData; // variable to hold long value
float m_fData; // variable to hold float value
string m_strData; // variable to hold string value
};

我目前正在通过消息队列发送一个 structData 数组。

structData arrStruct[MAX_SIZE];

这里的问题是结构中一次只有一个变量有用,其他两个都没用。因此,消息队列不必要地过载。我不能使用 union ,因为需要数据类型和值。我尝试使用模板,但它没有解决问题。我一次只能发送一种数据类型的结构数组。

template <typename T>
struct structData
{
char m_chType;
T m_Data;
}

structData<int> arrStruct[MAX_SIZE];

是否有一种标准方法来保存此类信息?

最佳答案

我不明白为什么不能使用 union 。这是标准方式:

struct structData
{
char m_chType; // variable to indicate the data type - long, float or string
union
{
long m_lData; // variable to hold long value
float m_fData; // variable to hold float value
char *m_strData; // variable to hold string value
}
};

通常情况下,您打开数据类型,然后访问对该类型有效的字段。

请注意,您不能将 string 放入 union 中,因为 string 类型是非 POD 类型。我已将其更改为使用一个指针,它可以是一个 C 零终止字符串。然后,您必须考虑根据需要分配和删除字符串数据的可能性。

关于c++ - 在单个结构中处理不同的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1102853/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com