Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

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


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

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...