简体   繁体   中英

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

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,...};

您可以,只需在您的 .cpp 文件中执行此操作:

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

好吧,我发现了一种不同的初始化方法,而无需在已经是意大利面条的 C++ 中创建额外的项目

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM