C++ declaring a static object in a class

百般思念 提交于 2019-12-01 23:51:02

You should initialize static var, the code:

class A // just an example
{
    int x;
public:
    A(){ x = 4; }
    int getX() { return x; }
};

class B
{
    static A obj1;  // <- Problem happens here
public:
    static void start();
};

A B::obj1; // init static var

int main()
{
    B::start();
}

void B::start()
{
    int x = obj1.getX();
}

As thinkerou said, you need to include the declaration of the variable:

A B::obj1;

For normal, non-static member variables you don't need this step because the variables are declared behind the scenes as part of the constructor. These variables are then tied to the instance of the class you just constructed. But static variables are not tied to any instance of a class; they are shared by all instances of a class. So constructors can't properly deal with them.

C++ gets around this by making you manually declare (and optionally initialize) any static member variables. Depending on where they are declared, they typically get constructed before your main() function starts, so they are available for use immediately.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!