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

后端 未结 3 1052
天涯浪人
天涯浪人 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.

    0 讨论(0)
  • 2021-02-04 01:39

    The reason you can't declare your array like that (const char* []) is that:

    • you can't have initializers in the class declaration, and so
    • the syntax const char* [] does not state how much space the compiler needs to allocate for each instance (your array is declared as instance variable).

    Besides, you probably want to make that array static, since it is in essence a constant value.

    0 讨论(0)
  • 2021-02-04 01:42

    Use the keyword static and external initialization to make the array a static member of the class:

    In the header file:

    class DataProvider : public SomethingElse
    {
        static const char* const mStringData[];
    
    public:
        DataProvider();
        ~DataProvider();
    
        const char* const GetData()
        {
            int index = GetCurrentIndex(); //work out the index based on some other data
            return mStringData[index]; //error checking and what have you omitted
        }
    
    };
    

    In the .cpp file:

    const char* const DataProvider::mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
    
    0 讨论(0)
提交回复
热议问题