How to initialize private static members in C++?

后端 未结 17 2262
忘掉有多难
忘掉有多难 2020-11-21 07:04

What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:

class foo
{
           


        
17条回答
  •  一向
    一向 (楼主)
    2020-11-21 07:31

    You can also include the assignment in the header file if you use header guards. I have used this technique for a C++ library I have created. Another way to achieve the same result is to use static methods. For example...

    class Foo
       {
       public:
         int GetMyStatic() const
         {
           return *MyStatic();
         }
    
       private:
         static int* MyStatic()
         {
           static int mStatic = 0;
           return &mStatic;
         }
       }
    

    The above code has the "bonus" of not requiring a CPP/source file. Again, a method I use for my C++ libraries.

提交回复
热议问题