为什么" '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"?
我正在查找在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
则相反。
相关文章:
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 收到错误"invalid use of non-static data member 'stu::n' "
- LNK1104:无法打开libpjproject-i386-Win32-vc14-Debug-Static.lib
- 我应该在 C++ 中何时/为什么使用 STATIC?
- 在VS2019项目中集成ImageMagick:x64-windows-static library
- 如何处理Boost Spirit X3导致Visual Studio 2019 "static initialization order fiasco"?
- "static char __ = []() -> char"的含义
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- 无法在 DLL 中链接 SDL2-static.lib
- 如何摆脱C++中未解析的外部符号"private: static char"错误?
- C++线程"Call to non-static member function without an object argument"
- 出现这种错误的原因是什么"invalid use of non-static data member "
- static是如何使用ClassA::m_variable处理所有类对象的
- LNK2001:未解析的外部符号public:static类std::vector
- 使用-static libstdc++时std::线程弱,因此在运行时会导致崩溃
- 你能初始化unique_ptrs "static const vectors"吗?(C++17 与 GCC 7.3)
- 未来C++标准支持"Declaring type template parameters with auto"
- 为什么异常不适用于 OSX 上的 gcc7 和 -static-libgcc?
- 为什么" 'static' may not be used when defining (as opposed to declaring) a static data member"?