【发布时间】:2011-09-22 10:09:55
【问题描述】:
如何在 C++ 中声明静态常量值? 我希望能够获得常量 Vector3::Xaxis,但我应该无法更改它。
我在另一个类中看到过如下代码:
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);
【问题讨论】: