跨文件共享静态变量:namespace vs class [英] Sharing static variables across files: namespace vs class
问题描述
这里有很多关于static vs global的问题,但我认为我的问题有点不同。
There are a lot of questions about static vs global here but I think my question is a bit different.
我想知道是否有办法分享
I want to know if there is a way to share a variable placed in a namespace across files the way static variables in a class can.
例如,我编码为:
//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
再次,是否有一种方法可以共享放置在命名空间中的变量文件的方式静态变量在一个类可以吗?我问的原因是因为我认为我可以通过使用::符号屏蔽自己与冲突的全局变量,只是发现我不能。和任何自卑的程序员一样,我相信我做错了。
Once again, is there a way to share a variable placed in a namespace across files the way static variables in a class can? The reason I ask is because I thought I would be able to shield myself from confliciting global variables by using :: notation, and just found out I could not. And like any self-disrespecting programmer, I believe I am doing it wrong.
推荐答案
是:
//bar.h
namespace bar
{
extern int kode;
}
在类之外
或 struct
, static
有完全不同的含义。它给出一个符号内部链接。因此,如果您声明了与 static
相同的变量,则实际上将为所有翻译单位获取不同的副本,而不是唯一的全局副本。
Outside of a class
or struct
, static
has a whole different meaning. It gives a symbol internal linkage. So if you declare the same variable as static
, you will actually get a different copy for all translation units, not a unique global.
请注意,您需要初始化变量一次:
Note that you'll need to initialize the variable once:
//bar.cpp
namespace bar
{
int kode = 1337;
}
这篇关于跨文件共享静态变量:namespace vs class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!