我正在寻找在C++中初始化静态地图的方法,并找到了这段代码:
struct A{
static map<int,int> create_map()
{
map<int,int> m;
m[1] = 2;
m[3] = 4;
m[5] = 6;
return m;
}
static const map<int,int> myMap;
};
const map<int,int> A:: myMap = A::create_map();
Run Code Online (Sandbox Code Playgroud)
但是,如果我将最后一行更改为
const static map<int,int> A:: myMap = A::create_map();
Run Code Online (Sandbox Code Playgroud)
编译器投诉:在定义(而不是声明)静态数据成员时,可能不会使用"静态"?
我想知道为什么?这背后的逻辑或推理是什么?
Ben*_*igt 16
static int a = 0; // grandfathered and still useful, provides static *LINKAGE*
// and static STORAGE DURATION
static int X::a = 0; // confusing and illegal, is it static LINKAGE
// or static STORAGE DURATION
// or static MEMBERSHIP?
Run Code Online (Sandbox Code Playgroud)
static在变量定义上使用时已经有了意义(在C中).对于学习C++的C程序员来说,有时会发现意义有所改变,但并非总是如此,这将是非常令人惊讶的.
所以新的含义(静态成员资格)只在类定义中有效(其中C不允许static关键字).