How to initialize private static members in C++?

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

    Also working in privateStatic.cpp file :

    #include 
    
    using namespace std;
    
    class A
    {
    private:
      static int v;
    };
    
    int A::v = 10; // possible initializing
    
    int main()
    {
    A a;
    //cout << A::v << endl; // no access because of private scope
    return 0;
    }
    
    // g++ privateStatic.cpp -o privateStatic && ./privateStatic
    

提交回复
热议问题