How to initialize private static members in C++?

后端 未结 17 2295
忘掉有多难
忘掉有多难 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:28

    I follow the idea from Karl. I like it and now I use it as well. I've changed a little bit the notation and add some functionality

    #include 
    
    class Foo
    {
       public:
    
         int   GetMyStaticValue () const {  return MyStatic();  }
         int & GetMyStaticVar ()         {  return MyStatic();  }
         static bool isMyStatic (int & num) {  return & num == & MyStatic(); }
    
       private:
    
          static int & MyStatic ()
          {
             static int mStatic = 7;
             return mStatic;
          }
    };
    
    int main (int, char **)
    {
       Foo obj;
    
       printf ("mystatic value %d\n", obj.GetMyStaticValue());
       obj.GetMyStaticVar () = 3;
       printf ("mystatic value %d\n", obj.GetMyStaticValue());
    
       int valMyS = obj.GetMyStaticVar ();
       int & iPtr1 = obj.GetMyStaticVar ();
       int & iPtr2 = valMyS;
    
       printf ("is my static %d %d\n", Foo::isMyStatic(iPtr1), Foo::isMyStatic(iPtr2));
    }
    

    this outputs

    mystatic value 7
    mystatic value 3
    is my static 1 0
    

提交回复
热议问题