Initializing Constant Static Array In Header File

删除回忆录丶 提交于 2019-11-28 19:42:21

问题


I have just found out that the following is not valid.

//Header File
class test
{
    const static char array[] = { '1', '2', '3' };
};

Where is the best place to initialize this?


回答1:


The best place would be in a source file

// Header file
class test
{
    const static char array[];
};

// Source file
const char test::array[] = {'1','2','3'};

You can initialize integer types in the class declaration like you tried to do; all other types have to be initialized outside the class declaration, and only once.




回答2:


You can always do the following:

class test {
  static const char array(int index) {
    static const char a[] = {'1','2','3'};
    return a[index];
  } 
};

A couple nice things about this paradigm:

  • No need for a cpp file
  • You can do range checking if you want to
  • You avoid having to worry about the static initialization fiasco



回答3:


//Header File 
class test 
{ 
    const static char array[];
}; 

// .cpp
const char test::array[] = { '1', '2', '3' }; 



回答4:


Now, in C++17, you can use inline variable

How do inline variables work?

A simple static data member(N4424):

struct WithStaticDataMember {
  // This is a definition, no out­of­line definition is required.
  static inline constexpr const char *kFoo = "foo bar";
};

In your example:

//Header File
class test
{
    inline constexpr static char array[] = { '1', '2', '3' };
};

should just work




回答5:


This is kind of an abuse of the system, but if you REALLY want to define it in the header file (and you don't have C++17), you can do this. It won't be a static member, but it will be a constant that only takes up storage per compilation unit (rather than per class instance):

(Put all of this code in the header file.)

namespace {
    const char test_init_array[] = {'1', '2', '3'};
}

class test {
public:
    const char * const array;

    test() : array(test_init_array) {}
};


来源:https://stackoverflow.com/questions/2117313/initializing-constant-static-array-in-header-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!