这里有很多关于静态与全局的问题,但我认为我的问题有点不同。
我想知道是否有一种方法可以像类中的静态变量那样跨文件共享放置在命名空间中的变量。
例如,我这样编码:
//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++;
}
}
}
所有这一切都产生了代码和kode:
Foo::code = 1,2,3,4
bar::kode = 0,0,1,1
再一次,有没有办法像类中的静态变量一样跨文件共享放置在命名空间中的变量?我问的原因是因为我认为我可以通过使用 :: 表示法来保护自己免受全局变量的冲突,但我发现我做不到。和任何不尊重自己的程序员一样,我相信我做错了。