【发布时间】:2018-03-14 14:56:40
【问题描述】:
我有 TestMethods.h
#pragma once
// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
class TestMethods
{
private:
static int nextNodeID;
// I tried the following line instead ...it says the in-class initializer must be constant ... but this is not a constant...it needs to increment.
//static int nextNodeID = 0;
int nodeID;
std::string fnPFRfile; // Name of location data file for this node.
public:
TestMethods();
~TestMethods();
int currentNodeID();
};
// Initialize the nextNodeID
int TestMethods::nextNodeID = 0;
// I tried this down here ... it says the variable is multiply defined.
我有 TestMethods.cpp
#include "stdafx.h"
#include "TestMethods.h"
TestMethods::TestMethods()
{
nodeID = nextNodeID;
++nextNodeID;
}
TestMethods::~TestMethods()
{
}
int TestMethods::currentNodeID()
{
return nextNodeID;
}
我在这里看过这个例子:Unique id of class instance
它看起来和我的几乎一模一样。我尝试了两种顶级解决方案。都不适合我。显然我错过了一些东西。谁能指出它是什么?
【问题讨论】:
-
在课堂上使用
static int nextNodeID = 0;有什么问题?你仍然可以在你的构造函数中增加它。 -
1) "我在这里试过了......它说变量是多重定义的。" 不要在标题中定义变量 - 在 . cpp 文件,所以它只定义一次。 2)“它说类内初始化程序必须是常量”您是否在启用 C++-11 的情况下进行编译?如果我没记错的话,这种语法在 C++-11 之前是无效的。
-
Nathan,问题在于它说“具有类内初始化程序的成员必须是 const”……但这并不是一个常量。
-
Algirdas,如果我把它放在类定义之外,它就不再是私有变量了。但是,我尝试了它并且它有效。我不知道如何判断我正在编译的 C++ 版本。我刚刚安装了VS community 2017。在“C++语言标准”中没有输入任何内容
-
哦,哎呀。忘了类初始化仍然不适用于非常量静态成员
标签: c++ class variables static