【问题标题】:Static constant members in a class C++C++ 类中的静态常量成员
【发布时间】: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);

【问题讨论】:

标签: c++ oop static constants


【解决方案1】:
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])。

如果您需要这个仅用于标头的模块,那么有一个基于模板的技巧 为您做 - 但如果您需要,最好单独询问。

干杯,

【讨论】:

    【解决方案2】:

    您需要在类声明之外初始化静态成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多