非常量静态成员变量的C ++初始化? [英] C++ initialization of non constant static member variable?

查看:113
本文介绍了非常量静态成员变量的C ++初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到成员变量 objectCount的限定错误。编译器还会返回 ISO C ++禁止在类中初始化非const静态成员。
这是主要类别:

I got a qualification error of the member variable 'objectCount'. The compiler also returns 'ISO C++ forbids in-class intialization of non-const static member'. This is the main class:

#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的树类:

This is the tree class which contains the non-const static 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


推荐答案

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

You have to define the static variable in the source file that includes this header.

#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 

这篇关于非常量静态成员变量的C ++初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆