我有一个foo包含整数的命名空间bar,声明如此...
foo.h中:
namespace foo {
int bar;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我foo.h只包含一个文件,这就可以了.但是当我foo.h从两个或更多文件中包含时出现问题:我收到链接器错误.我想出如果我声明bar为static,我可以包含foo.h在多个文件中.这对我来说似乎很奇怪,因为我不知道可以在命名空间内声明一个静态变量.(那有什么意思?)
为什么这样做?更重要的是,为什么没有它的工作没有 static?static在用于什么时意味着什么namespace?
在命名空间的上下文中是否static意味着什么?func2两种方法看起来是等效的。
// MyHeader.h
namespace TestNameSpace
{
int func1() { return 1; }
static int func2() { return 2; }
}
// SomeFile.cpp
#include "MyHeader.h"
// ...
int test1 = TestNameSpace::func1(); // 1
int test2 = TestNameSpace::func2(); // 2
Run Code Online (Sandbox Code Playgroud)