C++类中的静态常量成员
问题描述:
如何在C++中声明静态常量值? 我想能够得到常量Vector3 :: Xaxis,但我不应该能够改变它。C++类中的静态常量成员
我已经看到了另一大类下面的代码:
const MyClass MyClass::Constant(1.0);
我试图执行,在我的课:
static const Vector3 Xaxis(1.0, 0.0, 0.0);
但是我得到的错误
math3d.cpp:15: error: expected identifier before numeric constant
math3d.cpp:15: error: expected ‘,’ or ‘...’ before numeric constant
然后我尝试了一些更类似于我在C#中所做的事情:
static Vector3 Xaxis = Vector3(1, 0, 0);
但是我得到其他错误:
math3d.cpp:15: error: invalid use of incomplete type ‘class Vector3’
math3d.cpp:9: error: forward declaration of ‘class Vector3’
math3d.cpp:15: error: invalid in-class initialization of static data member of non-integral type ‘const Vector3’
我班上的重要组成部分,到目前为止是这样的
class Vector3
{
public:
double X;
double Y;
double Z;
static Vector3 Xaxis = Vector3(1, 0, 0);
Vector3(double x, double y, double z)
{
X = x; Y = y; Z = z;
}
};
如何实现我想在这里做什么?要有一个Vector3 :: Xaxis,它返回Vector3(1.0,0.0,0.0);
答
class Vector3
{
public:
double X;
double Y;
double Z;
static Vector3 const Xaxis;
Vector3(double x, double y, double z)
{
X = x; Y = y; Z = z;
}
};
Vector3 const Vector3::Xaxis(1, 0, 0);
注意,最后一行是定义,并应在一个实现文件 放(例如,[的.cpp]或[.CC])。
如果你需要这个仅用于标题模块,那么有一个基于模板的技巧, 为你做–但更好地询问,如果你需要它。
干杯&心连心,
+0
这样的作品,谢谢 – Hannesh
答
需要初始化类的声明之外的静态成员。
[C++在哪里初始化静态常量]可能的重复(http://stackoverflow.com/questions/2605520/c-where-to-initialize-static-const) – Troubadour