有很多关于静态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全局变量保护自己,刚刚发现我做不到。 而且,如同任何自我不尊重程序员,我相信我做错了。