【发布时间】:2017-09-04 13:08:32
【问题描述】:
如何在数组中存储不同类型的元素?
下面的示例可能会导致问题,因为“轮子”可以在 8 位数组中使用 32 位,因此它会填充前 4 个字段(如果我理解正确的话)。我可以使用移位运算符
class Car
{
public:
Car();
~Car();
private:
int32 wheels; // 32 bit Integer
bool canDrive; // 1 bit Boolean
int16 doors; // 16 bit Integer
}
Car()
{
wheels = 4;
canDrive = true;
doors = 2;
}
int main()
{
Car testCar;
int08 tmpArray[ARRAY_SIZE] = { 0 }; //8-bit Integer array
tmpArray[0] = testCar.wheels; //Store 32-bit Integer into 8-bit Integer
tmpArray[1] = testCar.canDrive; //Store 1-bit Boolean into 8-bit Integer
tmpArray[2] = testCar.doors; //Store 16-bit Integer into 8-bit Integer
/* Do something with tmpArray */
return 0;
}
【问题讨论】:
-
它不会“在 8 位中使用 32 位”任何东西。该值将被转换,可能会丢失数据。
-
你想在整数数组中插入一辆车吗?
-
C 和 C++ 数组只能保存相同类型的元素。如果您只需要获取表示
testCar结构的字节(例如以二进制形式将其转储到磁盘上),您可以使用int08 const * p_test_car_bytes = reinterpret_cast< int08 const * >(::std::addressof(testCar)); -
如果您认为可以将轮子存储在
int08类型中,只需将轮子声明更改为int08。 -
你想把Car序列化成
std::vector<std::uint8_t>吗?