ホームページ  >  に質問  >  本文

C++中静态成员变量如何访问?


class Tank
{
public:

    static int getCount()
    {
        return count;
    }

    static int count;//定义一个静态成员变量
};


int main(void)
{
    Tank::count = 0;

    //cout << Tank::getCount() << endl;   
    cout << Tank::count << endl;   //无法运行
    system("pause");
    return 0;
}

这段代码中,会出现链接错误,请问是哪里出错了?

迷茫迷茫2714日前557

全員に返信(3)返信します

  • 巴扎黑

    巴扎黑2017-04-17 13:01:47

    你的初始化是不是写错了,应该是

    int Tank::count = 0;
    int main(void)
    {
        cout << Tank::count << endl;   //无法运行
        system("pause");
        return 0;
    }
    

    初始化放main外面。

    返事
    0
  • ringa_lee

    ringa_lee2017-04-17 13:01:47

    看下把声明放到前面可以吗?

    返事
    0
  • PHPz

    PHPz2017-04-17 13:01:47

    class Tank
    {
    public:
    
        static int getCount()
        {
            return count;
        }
    
        static int count;//声明一个静态成员变量
    };
    
    //定义并初始化count
    int Tank::count = 0;
    
    int main(void)
    {
        
        Tank::count = 0;
    
        //cout << Tank::getCount() << endl;   
        cout << Tank::count << endl;   //无法运行
        system("pause");
        return 0;
    }

    返事
    0
  • キャンセル返事