Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare and initialize a static const array as a class member?

Tags:

c++

Pretty self-explanatory. The array is of an integral type, the contents are known and unchanging, and C++0x isn't allowed. It also needs to be declared as a pointer. I just can't seem to find a syntax that works.

The declaration in Class.hpp:

static const unsigned char* Msg;

Stuff in Class.cpp is really what I've tinkered with:

const unsigned char Class::Msg[2] = {0x00, 0x01}; // (type mismatch)
const unsigned char* Class::Msg = new unsigned char[]{0x00, 0x01}; // (no C++0x)

...etc. I've also tried initializing inside the constructor, which of course doesn't work because it's a constant. Is what I'm asking for impossible?

like image 348
ACK_stoverflow Avatar asked Jul 06 '12 17:07

ACK_stoverflow


People also ask

How do you declare a static array in CPP?

A typical declaration for an array in C++ is: type name [elements]; where type is a valid type (such as int , float ...), name is a valid identifier and the elements field (which is always enclosed in square brackets [] ), specifies the length of the array in terms of the number of elements.

Can static members be const?

A static data member can be of any type except for void or void qualified with const or volatile. You cannot declare a static data member as mutable.


2 Answers

// in foo.h class Foo {     static const unsigned char* Msg; };  // in foo.cpp static const unsigned char Foo_Msg_data[] = {0x00,0x01}; const unsigned char* Foo::Msg = Foo_Msg_data; 
like image 66
Michael Burr Avatar answered Oct 03 '22 23:10

Michael Burr


You are mixing pointers and arrays. If what you want is an array, then use an array:

struct test {    static int data[10];        // array, not pointer! }; int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

struct test {    static int *data; }; // cpp static int* generate_data() {            // static here is "internal linkage"    int * p = new int[10];    for ( int i = 0; i < 10; ++i ) p[i] = 10*i;    return p; } int *test::data = generate_data(); 
like image 34
David Rodríguez - dribeas Avatar answered Oct 04 '22 01:10

David Rodríguez - dribeas