如何在 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);