跨文件共享静态变量:命名空间VS级(Sharing static variables across

2019-06-24 07:25发布

有很多关于静态VS全球问题,在这里,但我想我的问题是有点不同。

我想知道是否有共享放置在一个命名空间跨越文件的方式静态变量的类可以变量的方式。

例如,我编写这样的:

//Foo.h
class Foo
{
  public:
  static int code;
  static int times_two(int in_);
};

namespace bar
{
  static int kode;
}

-

//Foo.cpp
int Foo::code = 0;

int Foo::times_two(int in_)
{
  bar::kode++;
  code++;
  return 2*in_;
}

-

//main.cpp
int main()
{
  cout << "Foo::code = " << Foo::code << endl;

  for(int i=2; i < 6; i++)
  {
    cout << "2 x " << i << " = " << Foo::times_two(i) << endl;
    cout << "Foo::code = " << Foo::code << endl;
    cout << "bar::kode = " << bar::kode << endl;

    if(i == 3)
    {
      bar::kode++;
    }
  }
}

所有这一切产生了这个代码和科德:

Foo::code = 1,2,3,4
bar::kode = 0,0,1,1

再次,有没有放在共享命名空间中的跨文件的方式静态变量在一个类可以变量的方法吗? 我想问的原因是因为我认为我将能够从使用::符号confliciting全局变量保护自己,刚刚发现我做不到。 而且,如同任何自我不尊重程序员,我相信我做错了。

Answer 1:

是:

//bar.h
namespace bar
{
  extern int kode;
}

一个外部classstructstatic有着完全不同的意义。 它给出了一个符号内部链接。 所以,如果你声明相同的变量作为static ,你会真正得到一个不同的副本,所有的翻译单位,而不是一个独特的全球性。

请注意,您需要一次初始化变量:

//bar.cpp
namespace bar
{
   int kode = 1337;
}


文章来源: Sharing static variables across files: namespace vs class