C++ where to initialize static const

前端 未结 5 1187
走了就别回头了
走了就别回头了 2020-11-27 11:17

I have a class

class foo {
public:
   foo();
   foo( int );
private:
   static const string s;
};

Where is the best place to initialize the

5条回答
  •  伪装坚强ぢ
    2020-11-27 11:18

    In a translation unit within the same namespace, usually at the top:

    // foo.h
    struct foo
    {
        static const std::string s;
    };
    
    // foo.cpp
    const std::string foo::s = "thingadongdong"; // this is where it lives
    
    // bar.h
    namespace baz
    {
        struct bar
        {
            static const float f;
        };
    }
    
    // bar.cpp
    namespace baz
    {
        const float bar::f = 3.1415926535;
    }
    

提交回复
热议问题