首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >初始化类的静态(非常量)变量。

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

Stack Overflow用户
提问于 2018-03-14 14:56:40
回答 1查看 40关注 0票数 0

我有TestMethods.h

代码语言:javascript
复制
#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

代码语言:javascript
复制
#include "stdafx.h"
#include "TestMethods.h"

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

我在这里看过这个例子:Unique id of class instance

看上去和我的差不多。我试过两种最好的解决方案。对我来说都不管用。很明显我漏掉了什么。有人能指出是什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-14 15:15:50

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

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

代码语言:javascript
复制
class ExampleClass {

private:
    inline static int counter = 0;
public:
    ExampleClass() {
        ++counter;
    }
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49280961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档