且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 C++ 中初始化 const 字符串的静态 const 数组

更新时间:2022-04-16 01:52:10

首先,你需要一个数组,而不是一个指针.

First of all, you need an array, not a pointer.

static const char * const days[] = {"mon", "tue", "wed", "thur",
                                       "fri", "sat", "sun"};

其次,你不能直接在类定义中初始化它.在类定义中,只保留以下内容:

Second of all, you can't initialize that directly inside the class definition. Inside the class definition, leave only this:

static const char * const days[]; //declaration

然后,在 .cpp 文件中,写入定义

Then, in the .cpp file, write the definition

const char * const Week::days[] = {"mon", "tue", "wed", "thur",
                                       "fri", "sat", "sun"};

C++11 更新现在您可以直接在类定义中初始化成员:

Update for C++11 Now you can initialize members directly in the class definition:

const char * const days[] = {"mon", "tue", "wed", "thur",
                                       "fri", "sat", "sun"};