初始化类的静态(非常量)变量。

时间:2018-03-14 14:56:40

标签: c++ class variables static

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

它看起来几乎和我的相同。我尝试了两种顶级解决方案。对我来说都不适用。显然我错过了一些东西。谁能指出它是什么?

1 个答案:

答案 0 :(得分:2)

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

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

class ExampleClass {

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