-
static const members
What's wrong with this?
Code:
namespace somenamespace
{
class CMyClass
{
// static members
public:
static const float ms_PI;
static const float ms_G;
static const float ms_G_to_mm_per_sec;
static const float ms_G_to_um;
static const float ms_mm_per_sec_to_um;
...
}
}
and in my implementation:
Code:
namespace somenamespace
{
// static variables that we'll only calculate the once
const float CMyClass::ms_PI = (float)3.14159265358979323846;
const float CMyClass::ms_G = 9.80665f;
const float CMyClass::ms_G_to_mm_per_sec = (ms_G / (2.0f * ms_PI));
const float CMyClass::ms_G_to_um = (ms_G / (2.0f * ms_PI * 2.0f * ms_PI));
const float CMyClass::ms_mm_per_sec_to_um = (1.0f / (2.0f * ms_PI));
// construction
CMyClass::CMyClass(void)
{
}
...
}
When I come to use my variables, they haven't been initialised completely - ms_PI looks OK but ms_G, ms_G_to_mm_per_sec, ms_G_to_um and ms_mm_per_sec_to_um are all 0.0 ... am I missing something here or is VS .NET 2003 messing me around? Any helpful hints?
Cheers all,
T
-
Re: static const members
Provide inline initializations...
EDIT: I think inline intializations is limited to integral types only.. But the below code runs fine on VC++ 6.0... (compiles on Comeau)
Code:
#include<iostream>
using std::cout;
class CMyClass
{
// static members
public:
static const float ms_PI;
static const float ms_G;
static const float ms_G_to_mm_per_sec;
static const float ms_G_to_um;
static const float ms_mm_per_sec_to_um;
};
// static variables that we'll only calculate the once
const float CMyClass::ms_PI = (float)3.14159265358979323846;
const float CMyClass::ms_G = 9.80665f;
const float CMyClass::ms_G_to_mm_per_sec = (ms_G / (2.0f * ms_PI));
const float CMyClass::ms_G_to_um = (ms_G / (2.0f * ms_PI * 2.0f * ms_PI));
const float CMyClass::ms_mm_per_sec_to_um = (1.0f / (2.0f * ms_PI));
int main()
{
cout << CMyClass::ms_PI << "\n";
cout << CMyClass::ms_G << "\n";
cout << CMyClass::ms_G_to_mm_per_sec << "\n";
}
It runs fine with or without namespaces...