类C+中的静态常量成员+; 如何在C++中声明静态常量值? 我希望能够得到常量Vector3::Xaxis,但我不能更改它
我在另一个类中看到了以下代码:类C+中的静态常量成员+; 如何在C++中声明静态常量值? 我希望能够得到常量Vector3::Xaxis,但我不能更改它,c++,oop,static,constants,C++,Oop,Static,Constants,我在另一个类中看到了以下代码: 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 con
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中所做的事情:
但是,我会遇到其他错误:
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)
请注意,最后一行是定义,应该放在实现文件中
(如[cpp]或[cc])
如果你只需要一个标题模块,那么有一个基于模板的技巧
为你做这件事——但如果你需要的话,最好单独问一下
干杯,您需要在类声明之外初始化静态成员 可能重复的
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;
}
};
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);