Mor*_*ork 9 c++ static namespaces class
这里有很多关于静态与全局的问题,但我认为我的问题有点不同.
我想知道是否有一种方法可以跨文件共享放置在命名空间中的变量,就像类中的静态变量一样.
例如,我编码:
//Foo.h
class Foo
{
public:
static int code;
static int times_two(int in_);
};
namespace bar
{
static int kode;
}
Run Code Online (Sandbox Code Playgroud)
-
//Foo.cpp
int Foo::code = 0;
int Foo::times_two(int in_)
{
bar::kode++;
code++;
return 2*in_;
}
Run Code Online (Sandbox Code Playgroud)
-
//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++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
所有这些都产生了代码和代码:
Foo::code = 1,2,3,4
bar::kode = 0,0,1,1
Run Code Online (Sandbox Code Playgroud)
再一次,是否有一种方法可以跨文件共享放置在命名空间中的变量,就像类中的静态变量一样?我问的原因是因为我以为我能够通过使用:: notation来保护自己免受冲突的全局变量的影响,并且发现我不能.和任何不敬自己的程序员一样,我相信我做错了.
Luc*_*ore 21
是:
//bar.h
namespace bar
{
extern int kode;
}
Run Code Online (Sandbox Code Playgroud)
一个之外class或者struct,static具有完全不同的意义.它给出了符号内部联系.因此,如果您声明相同的变量static,您将实际获得所有翻译单元的不同副本,而不是唯一的全局变量.
请注意,您需要初始化变量一次:
//bar.cpp
namespace bar
{
int kode = 1337;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13420 次 |
| 最近记录: |