initialization of static data member

Jan 22, 2011 at 6:54pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//class.h
class A
{  static int a;
   static int b[10];
public:
   static void set();
};

//class.cpp
#include"class.h" 
void A::set()
{
   a=0;
 for(int i=0;i<10;i++)
   b[i]=0;
}


my plan is to provide a static method to initialize static data, but it cannot compile. For variable a I find a simple way to initialize it in class.cpp file with int A::a=0. For array it is possible to int A::b[10]={0,1,2..}, but it is not appropriate for large array size. So what is wrong with my plan? it is ok to initialize all static data in class.cpp file and use it directly in main.cpp? Thanks a lot.
Last edited on Jan 22, 2011 at 9:13pm
Jan 22, 2011 at 8:44pm
Would you mind editing your post and putting the source inside code tags? It will make it a lot more legible and folks here will be more likely to look at it.
Jan 22, 2011 at 9:14pm
Thanks, I am new to C++ and this forum.
In fact, I just find it is better to set static data and methods as public, and I can assign different values to them when I use them. But still confusing why the above code doesn't work?
Last edited on Jan 22, 2011 at 9:18pm
Jan 22, 2011 at 10:27pm
static class variables need to be defined outside the class (somewhere in a cpp file)
as well as declared inside the class;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//class.h
class A
{  static int a;
   static int b[10];
public:
   static void set();
};

//class.cpp
#include"class.h" 
void A::set()
{
  //no need for this anymore
 /* a=0;
 for(int i=0;i<10;i++)
   b[i]=0;*/
}
//define the static variables.
//Note  that static Plain Old Data types like int  are zero initialised unless otherwise specified
int A:a
int A::b [10];
Jan 23, 2011 at 2:12am
yes, but what if I want to initialize b[10] with nonzero numbers? I am thinking to use a loop, but as I declare b[] array as private. That's why I was trying to add a public static method to set b[].
The question is: how to set private static array data members? Thanks a lot.
Jan 23, 2011 at 2:22am
guestgulkan, I just got it. I have to declare the static member data before using it, right? Now everything works as I expected, thanks a lot:)
Topic archived. No new replies allowed.