gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:04:49 29 4
gpt4 key购买 nike

我得到了成员变量“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

最佳答案

您必须在包含此 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++初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6718479/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com