tags:

views:

168

answers:

2

I intended to create a class which only have static members and static functions. One of the member variable is an array. Would it be possible to initialize it without using constructors? I am having lots of linking errors right now...

Class A{

public:
  static char a[128];
  static void do_something();

}

How would you initialize a[128]? Why can't I initialize a[128] by directly specifying its value like in C?

a[128={1,2,3,...};
+4  A: 

You can, just do this in your .cpp file:

char A::a[6] = {1,2,3,4,5,6};
Brian R. Bondy
is there a static initializer available?
vtd-xml-author
Yes. In your .cpp file: `char A::a[6] = {1,2,3,4,5,6}`
Dennis Zickefoose
@Jimmy: only as displyed
Brian R. Bondy
+1  A: 

Just wondering, why do you need to initialize it inside a constructor?

Commonly, you make data member static so you don't need to create an instance to be able to access that member. Constructors are only called when you create an instance.

Non-const static members are initialized outside the class declaration (in the implementation file) as in the following:


class Member
{
public:
    Member( int i ) { }
};

class MyClass
{
public:
    static int i;
    static char c[ 10 ];
    static char d[ 10 ];
    static Member m_;
};


int MyClass::i = 5;
char MyClass::c[] = "abcde";
char MyClass::d[] = { 'a', 'b', 'c', 'd', 'e', '\0' };
Member MyClass::m_( 5 );
jasonline
would it be possible to have a static initializer in C++?
vtd-xml-author