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

kif*_*iph 8 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;
}
Run Code Online (Sandbox Code Playgroud)

这是包含非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
Run Code Online (Sandbox Code Playgroud)

Mah*_*esh 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 
Run Code Online (Sandbox Code Playgroud)


Naw*_*waz 5

int Tree::objectCount = 0;
Run Code Online (Sandbox Code Playgroud)

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

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

int Tree::objectCount = 0;
Run Code Online (Sandbox Code Playgroud)