Static Member in Struct Array?

Jun 25, 2013 at 4:34am
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.
Jun 25, 2013 at 4:36am
You access the element with:
Speaker::numElem
Jun 25, 2013 at 4:56am
1
2
Speaker s[10];
Speaker::numElem = 0;


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

Using Code::Blocks GNU compiler.
Jun 25, 2013 at 7:16am
> 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 ;
Jun 25, 2013 at 12:12pm
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?
Jun 25, 2013 at 2:40pm
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
Jun 25, 2013 at 3:39pm
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 

Jun 25, 2013 at 10:14pm
Thanks, guys.
Topic archived. No new replies allowed.