我有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

它看起来几乎和我的一样。我尝试了两种最佳解决方案。都不适合我。显然我缺少了一些东西。谁能指出是什么?

最佳答案

您需要将TestMethods::nextNodeID的定义移动到cpp文件中。如果您将其包含在头文件中,那么每个包含头文件的文件都将在其中定义它,从而导致多种定义。

如果您有C ++ 17支持,则可以使用inline关键字在类中声明静态变量,例如

class ExampleClass {

private:
    inline static int counter = 0;
public:
    ExampleClass() {
        ++counter;
    }
};

10-04 16:28