为什么" 'static' may not be used when defining (as opposed to declaring) a static data member"?

why " 'static' may not be used when defining (as opposed to declaring) a static data member"?

本文关键字:static declaring to opposed member data when be not may used      更新时间:2023-10-16

我正在查找在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'不能在定义(与声明相反)静态数据成员时使用" ?

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

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关键字)。

声明一个类成员static意味着它被这个类的所有对象共享。

当您将static添加到类之外的变量定义时,这意味着该变量具有文件作用域,并且在该文件之外不可见。

如果允许的话

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

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

这和

没什么区别
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则相反。