Re: can't make static array member

From: Robert W Hand (rwhand_at_NOSPAMoperamail.com)
Date: 01/05/04


Date: Mon, 05 Jan 2004 12:53:42 -0500

On Mon, 5 Jan 2004 11:52:38 -0500, "Deej" <davidhere40@hotmail.com>
wrote:

>I'm trying to create a static array in a class called Molecule and then use
>it in my program but I keep gettnig errors. This is what I did to define the
>array inside the class:
>const static float charges[2] = {1,-1};
>
>then I tried to use it by doing this:
>
>float fl1 = Molecule::charges[0]*Molecule::charges[1];

I am having a little trouble understanding exactly what you did. Here
is an example that does compile. Perhaps you can compare it to your
code.

#include <iostream>
#define PRINT(X) (std::cout<<#X<<": "<<X<<'\n')

class Molecule
   {
   static const int charges[];

// You are not allowed to initialize charges,
// an array, here, if that is what you were trying.

   public:
      float f()const
         {
         return Molecule::charges[0]*Molecule::charges[1];
         }
// Nonsense member function to illustrate that such a line
// is ok.
   };
   
const int Molecule::charges[]={1, -1};

// Note definition lies outside the class definition.
   
int main()
   {
   Molecule m;
   PRINT(m.f()); // prints m.f(): -1
   }

Note that I changed charges to an array of int rather than an array of
float. I am uncertain about how you are going to use them, but aren't
they going to be integer valued?

Also, using single precision floating types (like float) in molecular
computing went out of style in the 1960's IIRC. (Anyway, I do
remember my research advisor telling me to stop using single precision
variables then.) So, if a variable is going to take only small
integers, use int. If it is going to take on non-integer values, use
double. Use long double if even greater precision is required.

Best wishes,

Bob