静态类成员得到"undefined reference"。不知道为什么
static class member gets "undefined reference". Don't know why
我不知道这段代码有什么问题。我有以下非常简单的课程:
class SetOfCuts{
public:
static LeptonCuts Leptons;
static ElectronCuts TightElectrons;
static ElectronCuts LooseElectrons;
//***
//more code
};
并且,例如,在相同的 .h 文件中定义了 ElectronCut 类型,如下所示:
struct ElectronCuts{
bool Examine;
//****
//other irrelevant stuff
};
我认为没有什么太复杂的。
我的理解是,在主程序中,我可以做:
SetOfCuts::LooseElectrons.Examine = true;
但是如果我这样做,我会得到:
undefined reference to `SetOfCuts::LooseElectrons'
相反,如果我这样做:
bool SetOfCuts::LooseElectrons.Examine = true;
我得到:
error: expected initializer before '.' token
我不知道为什么我无法访问结构的成员。我缺少一些关于静态数据成员的明显信息,但我不知道它是什么。
多谢。
任何静态引用也必须在特定源文件中声明(而不仅仅是在头文件中),因为在链接完成时它必须存在于某个地方。
例如,如果您的Foo.h
中有此内容
class SetOfCuts{
public:
static LeptonCuts Leptons;
static ElectronCuts TightElectrons;
static ElectronCuts LooseElectrons;
};
那么在Foo.cpp
你将拥有
#include <Foo.h>
LeptonCuts SetOfCuts::Leptons = whatever;
ElectronCuts SetOfCuts::ThighElectrons = whatever;
..
最后在你的主要.cpp你将能够做到
#include <Foo.h>
SetOfCuts::Leptons = whatever;
您
收到的"未定义引用"错误是一个链接器错误,表示您已经声明了静态数据成员,但实际上尚未在任何地方定义它们。 在C++中,使用静态变量有两个步骤 - 你首先在类中指定它,就像你所做的那样,然后必须实际在某个地方定义它。 这类似于在标头中定义函数的方式 - 在标头中对函数进行原型设计,然后在源文件中提供实现。
在您的情况下,在已实现 SetOfCuts
成员函数的源文件中,添加以下行:
LeptonCuts SetOfCuts::Leptons;
ElectronCuts SetOfCuts::TightElectrons;
ElectronCuts SetOfCuts:LooseElectrons;
这告诉C++静态成员实际上是在哪个翻译单元中定义的。 如果需要,还可以在此处指定构造函数参数。 请注意,您不要在此处重复 static
关键字。
希望这有帮助!
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 我不知道为什么这段代码会让核心被转储?
- 反转字符串.不知道为什么这个逻辑是错误的.C++
- 没有函数模板的实例与我不知道为什么的参数列表匹配
- if-else 语句仅按特定顺序工作,我不知道为什么
- DirectX 11 引擎在第三次代码改进后没有突然运行,我不知道为什么
- 函数抛出seg错误,我不知道为什么
- 我不知道为什么复制构造函数的调用在 c++ 中不稳定
- 随着时间的推移,我的程序越来越慢,我不知道为什么.内存泄漏
- 分段故障(核心转储)-不知道为什么
- "错误:在'.标记'之前出现预期的主表达式,我不知道为什么
- 我正在制作c ++代码,但发生错误我不知道为什么
- std::cout << glGetString(GL_RENDER) << std::endl;抛出错误但不GL_Renderer或GL_Verision,我不知道为什么?
- 不知道为什么它不会停止循环
- 我的Arduino串行命令行不起作用,我不知道为什么
- 我正在编写一个拆分为 3 的合并排序,我不知道为什么它不起作用
- C++单例模式代码无法运行,不知道为什么?
- 我不知道为什么我的矢量无法推回
- 罗马数字输出C++总是"-858993460",不知道为什么?
- 合成错误不知道为什么会发生这种情况,请检查一下并告诉我这是我的编码还是视觉工作室