C++ declaring a static object in a class

后端 未结 2 443
终归单人心
终归单人心 2021-01-18 06:21

I\'m trying to declare a static object of a class A that I wrote in a different class B, like this:

class A // just an example
{
    int x;
public:
    A(){          


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-18 06:42

    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();
    }
    

提交回复
热议问题