gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > static member array

#9011 - hnager - Sat Jul 26, 2003 3:20 pm

Hey all - I'm having trouble declaring/defining a static member array. Instead oif having every instance of the class have it's own copy of the array I wanted to have it static in the class - I don't have any problems declaring/defining a single static variable:

Code:
class Ant : public Sprite{

public:
   Ant(){};
   ~Ant(){}

...

private:
   static int ant_variable;


};

int Ant::ant_variable = 0;

That should work, right? Now how about an array?

Code:
static int ant_personality[10];


If I take a similar approach to a single variable I get the following error when I compile:

ant.h:153: redeclaration of `int Ant::ant_personality[10]'
ant.h:39: `int Ant::ant_personality[10]' previously declared here

As far as I know, I can't define the array int he class declaration, how else would it be done? THanks again, Howard

#9015 - Touchstone - Sat Jul 26, 2003 4:27 pm

Quote:
If I take a similar approach


You know, it would be easier if you sent the erroneous code. :)

Anyhow, this is how to do it:
Code:
class CMyClass
{
static int m_Array[];
};

int CMyClass::m_Array[10];

_________________
You can't beat our meat

#9016 - hnager - Sat Jul 26, 2003 4:36 pm

I didn't want to look bad - sending broken code and all ;) Anyhow - thanks for the response, how would I then go about adding the values to that array only once? (BTW - this isn't a singleton). Do I need to actually have to add each element by hand:

Code:
ant_personality[0] = ANT_MARCH;
ant_personality[1] = ANT_MARCH;

...


Or can I use the method that I would have used had this not been a memebr array:

Code:
int Ant::ant_personality[10] = { ANT_MARCH, ANT_MARCH, ...};


That didn't seem to work...

#9019 - Sweex - Sat Jul 26, 2003 4:53 pm

Try leaving the 10 out... so just like this:

Code:

int Ant::ant_personality[] = { ANT_MARCH, ANT_MARCH, ...};


Just might work...
_________________
If everything fails, read the manual: If even that fails, post on forum!

#9027 - hnager - Sat Jul 26, 2003 6:59 pm

Tried that actually - I get:

Code:
ant.h:153: redeclaration of `int Ant::ant_personality[]'
ant.h:39: `int Ant::ant_personality[10]' previously declared here


I thought that would have worked aswell...a workaround I can think of would be to use a static flag and have the first instance of the class initiate the array - but that seems like aa hack.

#9036 - hnager - Sat Jul 26, 2003 10:06 pm

Amazing what a errors a missing '}' will produce - oops/

Anyhow, this works well:

Code:
int Ant::ant_personality[10] = { ANT_MARCH, ANT_MARCH, ...};

thanks.