in-class static array initialization HOWTO?

J

Javi

Hello there!.
I would like to create a class with an array as attribute. This array
is the same for all the objects so I'd like to declare it as static,
but the problem is: where and how should I define the elements of the
array, in the constructor?.

I've tried the following code but It doesn't work at all:

class hamiltonian{

private:
matrix** operators; //OK. perfect
int alpha; //Perfect, of course;
static double coeffs[5]={1,1,1,0.5,0.5} // Here comes the crash

public:

/* destructor */
/* constructor */
}

Please, can anybody tell me how to declare/define a static array of
doubles within a class?.

Thanks everybody.
 
P

Peter Jansson

Javi said:
Please, can anybody tell me how to declare/define a static array of
doubles within a class?.

class hamiltonian
{
private:
static double coeffs[5];
};
double hamiltonian::coeffs[5]={1,1,1,0.5,0.5};

Regards,
Peter Jansson
 
M

mlimber

Javi said:
Hello there!.
I would like to create a class with an array as attribute. This array
is the same for all the objects so I'd like to declare it as static,
but the problem is: where and how should I define the elements of the
array, in the constructor?.

I've tried the following code but It doesn't work at all:

class hamiltonian{

private:
matrix** operators; //OK. perfect
int alpha; //Perfect, of course;
static double coeffs[5]={1,1,1,0.5,0.5} // Here comes the crash

public:

/* destructor */
/* constructor */
}

Please, can anybody tell me how to declare/define a static array of
doubles within a class?.

Thanks everybody.

// In the header file
class A {
static const double coeffs[5];
};

// in the cpp file:
const double A::coeffs[] = { 1, 2, 3, 4, 5 };

Cheers! --M
 
A

Alf P. Steinbach

* Javi:
class hamiltonian{

private:
matrix** operators; //OK. perfect
int alpha; //Perfect, of course;
static double coeffs[5]={1,1,1,0.5,0.5} // Here comes the crash

static double const coeffs[5];
public:

/* destructor */
/* constructor */
}

Semicolon.

If the above is in a header file, then place the definition in an
implementation file:

double const hamiltonian::coeffs[5] = {1, 1, 1, 0.5, 0.5};

Anyway, you can avoid much work by using std::vector and friends instead of
raw arrays and pointers.
 
J

Javi

Thanks a lot for your help. I'm in a hurry and have no time to look
for the answer in dozens of books.

Best regards to everybody.


Javi
 

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,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top