静态字符串文字表? [英] Static string literal table?

查看:46
本文介绍了静态字符串文字表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中创建全局 & 的正确方法是什么?字符串的静态表?

What is the correct way in C++ to create a global & static table of strings?

全局",我的意思是:可以从任何包含标题的文件中使用.但不是某些运行时创建的单一对象的一部分.

By "global", I mean: Useable from any file that includes the header. But not part of some run-time created singelton objcet.

通过静态",我的意思是:尽可能少地设置运行时间.只读存储器页中的数据.每个应用只有 1 个数据实例.

By "static", I mean: As little run time set up possable. Data in read only memory pages. Only 1 instance of data per app.

通过字符串",我的意思是:以空字符结尾的字符数组很好.std::string 会很好,但我认为不能按照上述方式完成.正确吗?

By "string", I mean: Null terminated array of chars is fine. std::string would be nice, but I don't think it can be done in terms of the above. Correct?

表"的意思是:我的意思是一个可索引的数组.所以我猜不是一张桌子本身.但在这一点上我很灵活.对想法持开放态度.

By "table", I mean: I mean an indexable array. So I guess not a table per-se. But I'm flexable on this point. Open to ideas.

C++",我的意思是:C++ 不是 C.(更新:C++98,不是 C++11)

By "C++", I mean: C++ not C. (Update: C++98, not C++11)

推荐答案

strings.h

extern const char* table[];

strings.cpp

const char* table[] = {
    "Stack",
    "Overflow",
}

<小时>

对此的另一种看法,将错误代码用于查找表:


Another take on this, using error codes for a lookup table:

err.h

#define ERR_NOT_FOUND    0x1004
#define ERR_INVALID      0x1005

bool get_err_msg(int code, const char* &msg);

err.cpp

typedef struct {
    int errcode;
    const char* msg;
} errmsg_t;

static errmsg_t errmsg_table[] = {
    {ERR_NOT_FOUND, "Not found"},
    {ERR_INVALID,   "Invalid"}
};

#define ERRMSG_TABLE_LEN  sizeof(errmsg_table)/sizeof(errmsg_table[0])

bool get_err_msg(int code, const char* &msg){
    msg = NULL;
    for (int i=0; i<ERRMSG_TABLE_LEN; i++) {
        if (errmsg_table[i].errcode == code) {
            msg = errmsg_table[i].msg;
            return true;
        }
    }
    return false;
}

ma​​in.cpp

#include <stdio.h>
#include "err.h"

int main(int argc, char** argv) {
    const char* msg;
    int code = ERR_INVALID;
    if (get_err_msg(code, msg)) {
        printf("%d: %s\n", code, msg);
    }
    return 0;
}

我确信有更多的 C++ 方法可以做到这一点,但我确实是一名 C 程序员.

I'm sure there is a more C++ way of doing this, but I'm really a C programmer.

这篇关于静态字符串文字表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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