Reputation: 11753
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!
Upvotes: 4
Views: 11744
Reputation: 19704
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'}} {}
Upvotes: 4
Reputation: 409176
If you have a C++11 compatible compiler, you should be able to use like this:
ABCD():ObjNum(3),getByte{'a','b','c','d','e','f','g','h'}
But if your compiler can't handle that you have to initialize the array manually in the constructor, either element by element or by having another array and then do e.g. memcpy
.
Edit: If your compiler cant handle the C++11 syntax, you're pretty much out of luck. However, GCC since at least version 4.4, and also VC++2010, do handle it. So unless you have requirements forcing you to use "ancient" compilers it shouldn't be a problem.
Upvotes: 1
Reputation: 2108
In C++03 you can change the member to be of type boost::array and initialize it in the constructor with a function that returns boost::array<char,8>
.
Upvotes: 1
Reputation:
It is better to abandon C arrays. In C++ it is better to use std::string. In this case:
class A
{
public:
A() : s("abcdefgh") {}
private:
std::string s;
}
In C++11 you can use std::array and use std::initializer_list
class A
public:
A() : s{'a','b','c','d','e','f','g','h'} {}
private:
std::array<8> s;
}
Upvotes: 1
Reputation: 1915
In C++11 you can initialize arrays like this:
ABCD() : getByte { 'a','b','c','d','e','f','g','h' }
{ ... }
Upvotes: 3