C++中静态成员变量如何访问?
迷茫
迷茫 2017-04-17 12:59:47
0
3
555

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

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

répondre à tous(3)
巴扎黑

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

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

初始化放main外面。

左手右手慢动作

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

PHPzhong
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;
}
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!