【问题标题】:initializing a static (non-constant) variable of a class.初始化类的静态(非常量)变量。
【发布时间】:2018-03-14 14:56:40
【问题描述】:

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

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

【问题讨论】:

  • 在课堂上使用static int nextNodeID = 0;有什么问题?你仍然可以在你的构造函数中增加它。
  • 1) "我在这里试过了......它说变量是多重定义的。" 不要在标题中定义变量 - 在 . cpp 文件,所以它只定义一次。 2)“它说类内初始化程序必须是常量”您是否在启用 C++-11 的情况下进行编译?如果我没记错的话,这种语法在 C++-11 之前是无效的。
  • Nathan,问题在于它说“具有类内初始化程序的成员必须是 const”……但这并不是一个常量。
  • Algirdas,如果我把它放在类定义之外,它就不再是私有变量了。但是,我尝试了它并且它有效。我不知道如何判断我正在编译的 C++ 版本。我刚刚安装了VS community 2017。在“C++语言标准”中没有输入任何内容
  • 哦,哎呀。忘了类初始化仍然不适用于非常量静态成员

标签: c++ class variables static


【解决方案1】:

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

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

class ExampleClass {

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 2014-06-06
    • 2011-08-22
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多