gpt4 book ai didi

c++ - 在 C++ 中组织静态数据

转载 作者:太空狗 更新时间:2023-10-29 20:17:09 24 4
gpt4 key购买 nike

我正在开发一些嵌入式软件,其中有一些关于“产品”的静态信息。由于某个产品的信息在执行期间永远不会改变,我想在编译时初始化这些数据结构以节省堆栈/堆上的一些空间。

我为数据创建了一个Product类,打算将系统中的所有产品做成一个巨大的数组,然后在这个结构中进行查找,但我还没有完全弄清楚如何让它工作。数组给我带来了很多麻烦。一些伪代码:

class Product {
int m_price;
int m_availability[]; // invalid, need to set a size
... etc

// Constructor grabbing values for all members
Product(int p, int a[], ...);
}

static const Product products[] =
{
Product(99, {52,30,63, 49}, ...), // invalid syntax
...
}

有没有办法让这样的东西发挥作用?我唯一能想到的就是按属性组织并跳过整个 Product 对象。我觉得这会使整个事情更难理解和维护。

有人对我如何最好地组织此类数据有任何建议吗?

谢谢。

最佳答案

老式的 C 风格静态结构数组听起来非常符合您的要求。在编译时初始化,零运行时开销,不使用堆栈或堆。 C 仍然是嵌入式世界的主要参与者并不是巧合。

所以(一个配方 - 有足够的空间来改变它的细节);

// in .h file
class Product {
public: // putting this first means the class is really a struct
int m_price;
int m_availability[4];
//.... (more)
};
extern const Product product_array[];
extern const int product_array_nbr;

// in .cpp file
const Product product_array[] =
{
{
23,
{56,1,2,4},
//....(more)
},
{
24,
{65,1,2,4},
//....(more)
},
//....(more)
};

const int product_array_nbr = sizeof(product_array)/sizeof(product_array[0]);

关于c++ - 在 C++ 中组织静态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7535743/

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