我有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
看上去和我的差不多。我试过两种最好的解决方案。对我来说都不管用。很明显我漏掉了什么。有人能指出是什么吗?
发布于 2018-03-14 15:15:50
您需要将TestMethods::nextNodeID的定义移到cpp文件中。如果将其包含在头文件中,则包含头文件的每个文件都将在其中定义它,从而导致多个防御。
如果您有C++17支持,可以使用inline关键字在类中声明静态变量,如下
class ExampleClass {
private:
inline static int counter = 0;
public:
ExampleClass() {
++counter;
}
};https://stackoverflow.com/questions/49280961
复制相似问题