静态类成员得到"undefined reference"。不知道为什么

static class member gets "undefined reference". Don't know why

本文关键字:不知道 为什么 reference undefined 静态类 成员      更新时间:2023-10-16

我不知道这段代码有什么问题。我有以下非常简单的课程:

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 关键字。

希望这有帮助!

相关文章: