简体   繁体   中英

Can't initialize static member in c++

When i run the code(first program),it shows a error that var is private member.I defined it is a static member so shouldn't be var initilized outside of the class.

#include <iostream>
using namespace std;

class example{
    private:
      static int var;
    public:
      example(){
          cout<< "exp is called"<< endl;
      };

};

int example::var =6;

int main(void)
{
    example exp1;
    cout<< exp1.var<<endl;
    exp1.var=5;
    example exp2;
    cout<< exp2.var<<endl;
    cout<< example::var<<endl;

    return 0;
}

but this code works succesfully;

#include <iostream>
using namespace std;
class MyClass{
   private:
      static int st_var;
   public:
      MyClass(){
         st_var++; //increase the value of st_var when new object is created
      }
      static int getStaticVar() {
         return st_var;
      }
};
int MyClass::st_var = 0; //initializing the static int
main() {
   MyClass ob1, ob2, ob3; //three objects are created
   cout << "Number of objects: " << MyClass::getStaticVar();
}

What's wrong in the code(first program)?

var is a private member variable. It cannot be accessed or viewed from outside the class. Only the class and friend functions can access private members.

One of the options you can do to access it is to add a public method that returns its value.

class example {
private:
    static int var;

public:
    example() {
        cout << "exp is called" << endl;
    }
    int getVar() {
        return var;
    }
};

And call it from main as follows:

cout << exp1.getVar() << endl;

There is no issue in the initialization of the static data member. the issue is you are trying to access private member outside the class.

you need to add getter and setter in order to access the private data member.

Demo

Tip: if you are using c++17 you can use inline variable to initialize static data member.

class Foo {
 private:
  inline static int x{};

 public:
  Foo() = default;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM