initializing a const array in a class

J

J. Campbell

I have a class that I want to contain a const data-member equivalent to eg:

int array[8] = {7,11,13,17,19,23,29,31};

What's the simplest way to create such a table inside a class?

Thanks,

Joe
 
G

Gianni Mariani

J. Campbell said:
I have a class that I want to contain a const data-member equivalent to eg:

int array[8] = {7,11,13,17,19,23,29,31};

What's the simplest way to create such a table inside a class?

Thanks,

Joe

How about this ?

const int array[8] = {7,11,13,17,19,23,29,31};

struct foo
{
const int (&m_array)[8];
foo()
: m_array( array )
{
}
};
 
J

Joe C

Gianni Mariani said:
J. Campbell said:
I have a class that I want to contain a const data-member equivalent to eg:

int array[8] = {7,11,13,17,19,23,29,31};

What's the simplest way to create such a table inside a class?

Thanks,

Joe

How about this ?

const int array[8] = {7,11,13,17,19,23,29,31};

struct foo
{
const int (&m_array)[8];
foo()
: m_array( array )
{
}
};

Gianni, Thanks. This works;-) I'm a little confused by the syntax. What
exactly does:
const int (&m_array)[8]
mean? and how does it differ from a:
const int* to the head of an array?

Thanks for your help/solution.

Joe
 
S

S. Richards

I have a class that I want to contain a const data-member equivalent to eg:

int array[8] = {7,11,13,17,19,23,29,31};

What's the simplest way to create such a table inside a class?

Thanks,

Joe

You can make it static and initialize it as follows:

class A
{
public:
static const int iarr[2];
};

const int A::iarr[2] = { 0, 1 };

Sheldon.
 
G

Gianni Mariani

Joe said:
J. Campbell said:
I have a class that I want to contain a const data-member equivalent to
eg:
int array[8] = {7,11,13,17,19,23,29,31};

What's the simplest way to create such a table inside a class?

Thanks,

Joe

How about this ?

const int array[8] = {7,11,13,17,19,23,29,31};

struct foo
{
const int (&m_array)[8];
foo()
: m_array( array )
{
}
};


Gianni, Thanks. This works;-) I'm a little confused by the syntax. What
exactly does:
const int (&m_array)[8]
mean?

it says: m_array is a reference to an 8 element array of const int.

and how does it differ from a:
const int* to the head of an array?

Little except that in the case of the array reference, the compiler
"knows" the size of the array - if there was code that depended on the
"array" instead of "pointer" behaviour, you preserved it's meaning using
the reference. You can also use this information to eliminate some
overrun errors.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top