strings.h
extern const char* table[];
strings.cpp
const char* table[] = {
"Stack",
"Overflow",
}
另取在此,使用错误代码的查找表:
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;
}
的main.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程序员。
你是什么意思表? – Pubby
全局数组? 'const char * table [SIZE];' –
我不认为_C_ vs _C++ _会在这里给出很大的区别,因为'std :: string'没有问题... –