简体   繁体   中英

initializing a static (non-constant) variable of a class.

I have 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.  

I have TestMethods.cpp

#include "stdafx.h"
#include "TestMethods.h"

TestMethods::TestMethods()
{
    nodeID = nextNodeID;
    ++nextNodeID;
}
TestMethods::~TestMethods()
{
}
int TestMethods::currentNodeID()
{
    return nextNodeID;
}

I've looked at this example here: Unique id of class instance

It looks almost identical to mine. I tried both the top solutions. Neither works for me. Obviously I'm missing something. Can anyone point out what it is?

You need to move the definition of TestMethods::nextNodeID into the cpp file. If you have it in the header file then every file that includes the header will get it defined in them leading to multiple defenitions.

If you have C++17 support you can use the inline keyword to declare the static variable in the class like

class ExampleClass {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM