static const member arrays

Jun 8, 2011 at 11:22pm
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.
Jun 9, 2011 at 12:34am
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.
Jun 9, 2011 at 12:57am
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 Jun 9, 2011 at 12:58am
Topic archived. No new replies allowed.