How do you declare arrays in a c++ header?

后端 未结 3 1057
天涯浪人
天涯浪人 2021-02-04 01:18

This is related to some other questions, such as: this, and some of my other questions.

In this question, and others, we see we can declare and initialise string arrays

3条回答
  •  余生分开走
    2021-02-04 01:37

    This is not possible in C++. You cannot directly initialize the array. Instead you have to give it the size it will have (4 in your case), and you have to initialize the array in the constructor of DataProvider:

    class DataProvider {
        enum { SIZEOF_VALUES = 4 };
        const char * values[SIZEOF_VALUES];
    
        public:
        DataProvider() {
            const char * const v[SIZEOF_VALUES] = { 
                "one", "two", "three", "four" 
            };
            std::copy(v, v + SIZEOF_VALUES, values);
        }
    };
    

    Note that you have to give up on the const-ness of the pointers in the array, since you cannot directly initialize the array. But you need to later set the pointers to the right values, and thus the pointers need to be modifiable.

    If your values in the array are const nevertheless, the only way is to use a static array:

    /* in the header file */
    class DataProvider {
        enum { SIZEOF_VALUES = 4 };
        static const char * const values[SIZEOF_VALUES];
    };
    
    /* in cpp file: */
    
    const char * const DataProvider::values[SIZEOF_VALUES] = 
        { "one", "two", "three", "four" };
    

    Having the static array means all objects will share that array. Thus you will have saved memory too.

提交回复
热议问题