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

后端 未结 2 781
深忆病人
深忆病人 2020-12-24 06:03

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

From week.h (showing only relevant parts):

class Week {
  private:
    static          


        
2条回答
  •  独厮守ぢ
    2020-12-24 07:08

    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

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

提交回复
热议问题