c++ question, how to define a member array, and it's size, outside of the class dec..
My code looked like this. Not exactly like this, but this is a shorter example:
---------------
#include <iostream>
#define NUM_NAMES 2
class A
{
public:
static char * names[NUM_NAMES];
};
char * A::names[NUM_NAMES] = { "Bob", "Sue" };
int main(int argc, char ** argv)
{
for (int i = 0; i < NUM_NAMES; i++)
{
std::cout << A::names[i] << std::endl;
}
return 0;
}
-----------------------
It works fine, but if I want to add another name, I have to do that, and I have to change NUM_NAMES. If these become out of sync, I could get into trouble.
So, I changed it to this:
--------------------------
#include <iostream>
class A
{
public:
static char * names[];
};
char * A::names[] = { "Bob", "Sue" };
int NUM_NAMES = sizeof(A::names) / sizeof(char *);
int main(int argc, char ** argv)
{
for (int i = 0; i < NUM_NAMES; i++)
{
std::cout << A::names[i] << std::endl;
}
return 0;
}
------------------------------
I thought this was more c++ like. Doing it this way, to add another name to the list, you just do that. NUM_NAMES takes care of itself.
Unfortunately, it segfaults. At least, the real program does. It only segfaults at the very end, but I've traced it back to here. The memory does not get set aside like I hoped it would.
How can I have static member variable array, and be able to define the array, and it's size, outside of the class declaration?
I could just put Bob and Mary and everyone else, inside the class declaration, but the real version is very long, and that would be ugly and not very c++ like. Also, I keep the declaration and the implementations in different files, making it more inconvenient to edit both NUM_NAMES and the names themselves.
Thanks in advance.
Last edited by Winter Knight; 01-20-2007 at 09:53 AM.
|