开发者

Initialize a static member ( an array) in C++

I 开发者_StackOverflow社区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,...};


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

char A::a[6] = {1,2,3,4,5,6};


If your member isn't going to change after it's initialized, C++11 lets you keep it all in the class definition with constexpr:

class A
{
public:
  static constexpr const char a[] = {1,2,3}; // = "Hello, World"; would also work
  static void do_something();
};


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 );


With C+++17 and up, you can initialize it inline, as follows

class A
{
public:
  inline static char a[2]={1,1};
  static void do_something();
};


Well, I have found out a different way to initialize without resorting to create additional items in the already spaghetti C++

char fred::c[4] = {};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜