making a constant array in c++

前端 未结 2 2014
走了就别回头了
走了就别回头了 2020-12-24 05:31

Is there any reason why codeblocks is telling me that I can\'t make an array? I\'m simply trying to do:

const unsigned int ARRAY[10] = {0,1,2,3,4,5,6,7,8,9};         


        
2条回答
  •  醉梦人生
    2020-12-24 06:16

    Since this is a private member variable in a class (according to the comment), this is indeed not allowed in C++03.

    C++0x, partially supported by many modern compilers, allows the following to compile:

    class C
    {
        const unsigned int ARRAY[10];
     public:
        C() : ARRAY{0,1,2,3,4,5,6,7,8,9} {}
    };
    int main()
    {
        C obj; // contains a non-static const member: non-assignable 
    }
    

    However, non-static const members only make sense if they contain different values in different instances of the class. If every instance is to contain the same {0,1,2,3,4,5,6,7,8,9}, then you should make it static, which also makes it possible to do this in C++98:

    class C
    {
        static const unsigned int ARRAY[10];
     public:
        C() {}
    };
    const unsigned int C::ARRAY[10] = {0,1,2,3,4,5,6,7,8,9};
    int main()
    {
        C obj;
    }
    

提交回复
热议问题