How to initialize a const char array data member with C++?

c++

Solution

In C++11 you can initialize it like this:

ABCD() : ObjNum(3), getByte{'a','b','c','d','e','f','g','h'} {}

If you are going to use C++11, though, it would be better to use `std::array` as others have suggested in the comments. You could then define the array like:

const std::array<unsigned char, 8> getByte;

and initialize it in this way (note the double braces):

ABCD() : ObjNum(3), getByte{{'a','b','c','d','e','f','g','h'}} {}

Problem

I have a question related to C++ class member initialization. The following code illustrates my question: ``` class ABCD { public: ABCD():ObjNum(3){}; ~ABCD() {}; static const unsigned char getByte[8]; const int ObjNum; }; const unsigned char ABCD::getByte[8] = { 'a','b','c','d','e','f','g','h' }; int main() { ABCD test; cout<<test.getByte[3]<<endl; return 0; } ``` The above codes work very well, but now if I do not set getByte[8] as static, how could I initialize the class? I have tried in this way, but failed: ``` class ABCD { public: ABCD():ObjNum(3),getByte('a','b','c','d','e','f','g','h') { }; ~ABCD() {}; const unsigned char getByte[8]; const int ObjNum; }; int main() { ABCD test; cout<<test.getByte[3]<<endl; return 0; } ``` The error I have obtained is as follows: ``` error C2536: 'ABCD::ABCD::getByte' : cannot specify explicit initializer for arrays ``` I understand the reason why I got the error, but I do not know how to fix it. Any idea? Thanks!

Original source

Related problems