我一直在寻找了方式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();
但是,如果我改变最后一行
const static map<int,int> A:: myMap = A::create_map();
编译器的抱怨:定义当(相对于声明)静态数据成员”“静止”可以不使用?
我想知道为什么? 什么是这背后的逻辑和推理?
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?
static
已经有含义(在C)上的变量定义中使用时。 这将是C程序员学习C ++的发现意义非常令人吃惊有时被改变,但并非总是如此。
因此,新的含义(静态成员)只有类定义(其中C没有让里面活跃的static
关键字)。
它没有比不同
struct A
{
static int x;
}
int A::x; //legal
static int A::x; //illegal
一切是在这个最小的,在概念上是相同的,例如刚刚抛出多个关键字。 一个static
成员只能声明static
的类定义中。
该
const map<int,int> A:: myMap = A::create_map();
在类外是只是一个定义static
成员A::myMap
。 额外的static
是没有意义的存在。
这背后的原因可能是为了避免混淆-一个static
自由变量是怎样的一个“私有”变量(一个翻译单元)。 甲构件static
是相反的。
声明类部件static
意味着它是这个类的所有对象之间共享。
当您添加static
的变量定义一个类以外,它意味着这个变量具有文件范围内,而不是这个文件外可见。
如果将被允许
const static map<int,int> A:: myMap = A::create_map();
这将意味着,你有一个静态成员变量,这是不是这个文件的外部可见。 这只是没有任何意义。
文章来源: why “ 'static' may not be used when defining (as opposed to declaring) a static data member”?