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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6536805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:19:55  来源:igfitidea点击:

Initializing a static const array of const strings in C++

c++compiler-errorsinitializationconst

提问by Nick

I am having trouble initializing a constant array of constant strings.

我在初始化常量字符串的常量数组时遇到问题。

From week.h (showing only relevant parts):

从week.h(仅显示相关部分):

class Week {
  private:
    static const char *const *days = { "mon", "tue", "wed", "thur",
                                       "fri", "sat", "sun" };
};

When I compile I get the error "excess elements in scalar initializer". I tried making it type const char **, thinking I messed up the 2nd const placement, but I got the same error. What am I doing wrong?

编译时出现错误“标量初始值设定项中的元素过多”。我试着让它输入 const char **,以为我搞砸了第二个 const 位置,但我得到了同样的错误。我究竟做错了什么?

回答by Armen Tsirunyan

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

Then, in the .cpp file, write the definition

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

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

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

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

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

回答by marni

For C++11, you canmake the initialisation inside your class declaration, in your .hfile. However, you will need to include constexpr in your .cppfile too. Example for the case above:

对于C++11,您可以.h文件中的类声明中进行初始化。但是,您还需要在.cpp文件中包含 constexpr 。上述案例的示例:

In your week.h file, write:

在您的 week.h 文件中,写入:

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

In your week.cpp file, write somewhere:

在你的 week.cpp 文件中,写下某处:

constexpr const char* const Week::days[];

Make sure you enable C++11, e.g. compile with

确保您启用C++11,例如编译

g++ -std=c++11 week.cpp

g++ -std=c++11 week.cpp