Static Member in Struct Array?

Here's the definition of my struct:

1
2
3
4
5
6
7
8
9
10
11
struct Speaker
{
    static int numElem;
    string name;
    int number; // Phone
    string topic;
    float fee;
};

// IN main() FUNCTION
Speaker s[10];


The goal is for numElem to keep track of how many of the 10 elements are in use. However, I'm not sure the proper way to access the element, if it's even possible. Does anybody know if I can do this?

Thanks.
You access the element with:
Speaker::numElem
1
2
Speaker s[10];
Speaker::numElem = 0;


Give the error:
"Undefined reference to 'Speaker::numElem'"

Using Code::Blocks GNU compiler.
> Give the error: "Undefined reference to 'Speaker::numElem'"

It is not defined. In an implementation file (for instance speaker.cpp), define it. For instance:

int Speaker::numElem = 0 ;
Of course. I completely forgot I had to put the type as well.

Why do I have to put it outside the main function? Is that because it's a global initializer?
Is that because it's a global initializer?
I don't know what you mean by that, but numElem is a global variable that must exists exactly once within the program.

static int numElem just tells the compiler that a variable with that name and type (is supposed to) exist somewhere within your program


By the way: with numElem being static you cannot have a second array of type Speaker!

Better use a containter (like vector) or another struct for the array + the number of elements
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
extern int s ; // declaration

namespace A
{
    extern int s ; // declaration
}

struct B
{
    static int s ; // declaration
};

int s = 1 ; // definition

int A::s = 2 ; // definition

int B::s = 3 ; // definition 

Thanks, guys.
Topic archived. No new replies allowed.