C ++类中的静态常量成员 [英] Static constant members in a class C++

查看:138
本文介绍了C ++类中的静态常量成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++中声明静态常量值? 我希望能够获得常量Vector3 :: Xaxis,但我不应该对其进行更改.

How do I declare static constant values in C++? I want to be able to get the constant Vector3::Xaxis, but I should not be able to change it.

我在另一堂课中看到了以下代码:

I've seen the following code in another class:

const MyClass MyClass::Constant(1.0);

我试图在课堂上实现这一点:

I tried to implement that in my class:

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#中类似的操作:

Then I tried something more similar to what I'd do in 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’

到目前为止,我班上的重要部分都像这样

My important parts of my class so far look like this

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);

How do I achieve what I'm trying to do here? To have a Vector3::Xaxis which returns 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]).

Note that last line is the definition and should be put in an implementation file (e.g. [.cpp] or [.cc]).

如果仅标题模块需要此功能,则可以使用基于模板的技巧 为您做–但是最好单独询问一下.

If you need this for a header-only module then there is a template-based trick that do it for you – but better ask separately about that if you need it.

干杯hth.,

这篇关于C ++类中的静态常量成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆