在C ++中组织静态数据 [英] Organizing static data in C++

查看:125
本文介绍了在C ++中组织静态数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on some embedded software where there is some static information about "products". Since the information for a certain product never changes during execution I would like to initialize these data structures at compile time to save some space on the stack/heap.

产品类的数据,打算在系统中的所有产品做一个巨大的数组,然后在这个结构中查找,但我还没有搞清楚如何得到它工作。这些数组给我带来了麻烦。一些伪代码:

I made a Product class for the data, intending to make a huge array of all the products in the system and then do lookups in this structure, but I haven't figured out quite how to get it working. The arrays are giving me loads of trouble. Some psuedo code:

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 对象。我觉得会使整个事情更难理解和维护。

Is there a way to making something like this work? The only thing I can think of would be to organize by attribute and skip the whole Product object. I feel that would make the whole thing harder to understand and maintain though.

有没有人对如何最好地组织这类数据有任何建议?

Does anyone have any suggestions on how I might best organize this kind of data?

谢谢。 / p>

Thank you.

推荐答案

一个古老的C风格的结构体静态数组听起来像是完美匹配你的要求。在编译时初始化,零运行时开销,不使用堆栈或堆。

An old school C style static array of structs sounds like a perfect match to your requirements. Initializes at compile time, zero runtime overhead, no use of stack or heap. It's not a co-incidence that C is still a major player in the embedded world.

所以(一个配方 - 有足够的范围来改变这个细节);

So (one recipe - plenty of scope to change the details of this);

// 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 ++中组织静态数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆