为什么在定义(而不是声明)静态数据成员时可能不会使用“'static'”?

时间:2013-03-05 22:12:32

标签: c++ static

我正在寻找在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'吗?

我想知道为什么?这背后的逻辑或推理是什么?

3 个答案:

答案 0 :(得分: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?
当在变量定义上使用时,

static已经具有含义(在C中)。对于学习C ++的C程序员来说,有时会发现意义有所改变,但并非总是如此,这将是非常令人惊讶的。

所以新的含义(静态成员资格)只在类定义中有效(其中C不允许static关键字)。

答案 1 :(得分:3)

无异
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则相反。

答案 2 :(得分:2)

声明类成员static表示它在此类的所有对象之间共享。

static添加到类之外的变量定义时,表示此变量具有文件范围,并且在此文件外部不可见。

如果允许

const static map<int,int> A:: myMap =  A::create_map();

这意味着,您有一个静态成员变量,该变量在此文件之外是不可见的。这没有意义。