如何用C ++初始化一个const char数组数据成员? [英] How to initialize a const char array data member with C++?
问题描述
我有一个与C ++类成员初始化相关的问题。以下代码说明了我的问题:
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;
}
上面的代码工作得很好,但现在如果我没有设置getByte [ 8] as static,我如何初始化类?我以这种方式尝试,但失败:
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;
}
我获得的错误如下:
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!
推荐答案
在C ++ 11中,您可以这样初始化:
In C++11 you can initialize it like this:
ABCD() : ObjNum(3), getByte{'a','b','c','d','e','f','g','h'} {}
如果你打算使用C ++ 11,最好使用 std :: array
,因为其他人在评论中建议。然后可以像下面这样定义数组:
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'}} {}
这篇关于如何用C ++初始化一个const char数组数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!