static const member arrays

Why can't I do this?

1
2
3
struct A{
    static const int mStatic[] = { 1,3,5 };
};


Seems I have to do this:
1
2
3
4
struct A{
    static const int mStatic[];
};
const int A::mStatic[] = { 1,3,5 };


Is there any way to move the bracketed definition 1,3,5 back into the struct body? I would rather not have to go looking out of the struct definition and it glugs up my header file.
I don't think so. I'm just learning about data structures and classes, and the compiler error I got from trying to use the first of the two is :

Error E2233 file.cpp 6: Cannot initialize a class member here


Now, like I said, I'm just leraning all of this, and hopefully an experienced member can clear this all up, but just from that error alone, I would assume that you cannot initialize members in the class itself.

I don't know why, and like I said, someone who knows what they are talking about will hopefully explain all of this.
You can only define static const integral values (i.e. short, int, long, bool, char, instance of an enum) within a struct. You can't declare static const arrays of integral values within a struct, unfortunately.

Since your array is so short, you might consider doing this:

1
2
3
4
5
struct A{
   static const int m1 = 1;
   static const int m2 = 3;
   static const int m3 = 5;
};


Otherwise, I guess you'll have to live with defining the array outside the struct.
Last edited on
Topic archived. No new replies allowed.