C ++初始化非常量静态成员变量?

时间:2011-07-16 15:52:46

标签: c++ static const

我得到了成员变量'objectCount'的资格错误。编译器还返回'ISO C ++禁止非const静态成员的类内初始化'。 这是主要的课程:

#include <iostream>
#include "Tree.h"
using namespace std;

int main()
{
    Tree oak;
    Tree elm;
    Tree pine;

    cout << "**********\noak: " << oak.getObjectCount()<< endl;
    cout << "**********\nelm: " << elm.getObjectCount()<< endl;
    cout << "**********\npine: " << pine.getObjectCount()<< endl;
}

这是包含非const静态objectCount:

的树类
#ifndef TREE_H_INCLUDED
#define TREE_H_INCLUDED

class Tree
{
    private:
        static int objectCount;
    public:
        Tree()
        {
            objectCount++;
        }
        int getObjectCount() const
        {
            return objectCount;
        }
    int Tree::objectCount = 0;
}
#endif // TREE_H_INCLUDED

3 个答案:

答案 0 :(得分:16)

您必须在源文件中定义包含此标头的静态变量。

#include "Tree.h"

int Tree::objectCount = 0;  // This definition should not be in the header file.
                            // Definition resides in another source file.
                            // In this case it is main.cpp 

答案 1 :(得分:4)

int Tree::objectCount = 0;

上面的行应该在课外,在.cpp文件中,如下所示:

//Tree.cpp 
#include "Tree.h"

int Tree::objectCount = 0;

答案 2 :(得分:3)

您需要在范围之外的单个C ++文件中定义它,而不是在标题中。

int Tree::objectCount = 0;
int main()
{
    Tree oak;
    Tree elm;
    Tree pine;

    cout << "**********\noak: " << oak.getObjectCount()<< endl;
    cout << "**********\nelm: " << elm.getObjectCount()<< endl;
    cout << "**********\npine: " << pine.getObjectCount()<< endl;
}

#ifndef TREE_H_INCLUDED
#define TREE_H_INCLUDED

class Tree
{
    private:
        static int objectCount;
    public:
        Tree()
        {
            objectCount++;
        }
        int getObjectCount() const
        {
            return objectCount;
        }
}
#endif // TREE_H_INCLUDED