外部类变量导致编译器错误

extern class variable causes compiler error

本文关键字:编译器 错误 类变量 外部      更新时间:2023-10-16

我有一个头文件头。hh包含这些定义(我正在尝试实现单例模式):

#ifndef HEAD_HH
#define HEAD_HH
class X
{
private:
  X() : i(0) {}
public:
  static X &instance()
  {
    static X x;
    return x;
  }
  int i;
};
#endif

我的实现impl。Cc是这样的:

#include "head.hh"
X &iks = X::instance();
iks.i = 17;
int main(int argc, char **argv)
{
  return 0;
}

我认为这段代码是正确的,但是我得到编译器错误(使用g++)

impl.cc:5:1: error: ‘iks’ does not name a type
 iks.i = 17;

谁能告诉我为什么我可以创建一个引用从静态::instance(),但不使用它的任何东西?(如果我在第五行注释,一切正常)

不能在全局范围内赋值。它必须是函数的一部分,例如:

// ...
iks.i = 17; // ERROR! Assignment not in the scope of a function
int main(int argc, char **argv)
{
    iks.i = 17;
//  ^^^^^^^^^^^ This is OK, we're inside a function body
    return 0;
}