2011-07-16 126 views
7

我得到了成员变量'objectCount'的限定错误。编译器还返回'ISO C++禁止非常量静态成员的类内部初始化'。 这是主类:非常量静态成员变量的C++初始化?

#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 
+0

有是未在任何建议答案中的提到的另一替代写这段文字的时间,它可以让你把所有的东西都保存在一个单一的标题**中。看看[这个SO答案](http://stackoverflow.com/a/33618854/3041008)中的例子,它完美地映射到你的例子。 – mucaho

回答

14

你必须定义包括该包头中的源文件中的静态变量。

#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 
+0

仍然存在以下错误'objectCount'声明中有两个或多个数据类型' – kifcaliph

+0

我忘了把这行代码放在int'Tree :: objectCount = 0;'类之外,我忘了用分号结尾的头文件类 谢谢你 – kifcaliph

+0

为什么这个变量必须在类之外声明?我试图定义和初始化一个私有变量,并且我得到了同样的错误。我该怎么在课外做这个? – dangerChihuahua007

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 
4
int Tree::objectCount = 0; 

上面行应该是在类的外部,并且在.cpp文件,如下所示:

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

int Tree::objectCount = 0;