【发布时间】:2011-10-06 19:17:31
【问题描述】:
我收到成员变量“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;
}
这是包含非常量静态 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
【问题讨论】:
-
在撰写本文时,任何建议的答案中都没有提到另一种选择,它允许您将所有内容保留在一个单个标题中。请参阅this SO answer 中的示例,它完美地映射到您的示例。