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

2023-12-29

我收到成员变量“objectCount”的限定错误。编译器还返回“ISO 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;
}

这是包含非常量静态 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

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

#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 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++非常量静态成员变量的初始化? 的相关文章

随机推荐