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

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

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

From week.h (showing only relevant parts):

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?

回答1:

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. Iside the class definition, leave only this:

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

Then, in the .cpp file, write the definition

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

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"}; 


回答2:

For C++11, you can make the initialisation inside your class declaration, in your .h file. However, you will need to include constexpr in your .cpp file too. Example for the case above:

In your week.h file, write:

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

In your week.cpp file, write somewhere:

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

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

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!