这里有很多关于静态与全局的问题,但我认为我的问题有点不同。
我想知道是否有一种方法可以像类中的静态变量那样跨文件共享放置在命名空间中的变量。
例如,我这样编码:
//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
再一次,有没有办法像类中的静态变量那样跨文件共享放置在命名空间中的变量?我问的原因是因为我认为我可以通过使用::表示法来保护自己免受冲突的全局变量的影响,但我发现我做不到。和任何自卑的程序员一样,我相信我做错了。
最佳答案
是的:
//bar.h
namespace bar
{
extern int kode;
}
在 class
或 struct
之外,static
具有完全不同的含义。它给出了符号内部链接。因此,如果您将同一个变量声明为 static
,您实际上会为所有翻译单元获得不同的拷贝,而不是唯一的全局拷贝。
请注意,您需要一次初始化变量:
//bar.cpp
namespace bar
{
int kode = 1337;
}
关于c++ - 跨文件共享静态变量 : namespace vs class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10534991/