Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
231 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...