Static constant members in a class C++

前端 未结 2 1835
[愿得一人]
[愿得一人] 2021-01-28 16:08

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 cod

相关标签:
2条回答
  • 2021-01-28 16:16

    You need to initialize static members outside of class declaration.

    0 讨论(0)
  • 2021-01-28 16:36
    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);
    

    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.

    Cheers & hth.,

    0 讨论(0)
提交回复
热议问题