简体   繁体   English

在 C++ 的结构中声明 static arrays

[英]Declare static arrays in a struct right in C++

I tried to declare static array:我试图声明 static 数组:

#include <iostream>
#include <string.h>
using namespace std;

struct tagData{
  static string tags[];
};

int main(){
  tagData::tags[3];
  tagData::tags[0] = "default";
  tagData::tags[1] = "player";
  tagData::tags[2] = "enemy";
  return 0;
}

But as the result an error occurred:但结果发生了错误:

*Path*\cczPqyfY.o:main.cpp:(.text+0x1e): undefined reference to `tagData::tags[abi:cxx11]'
*Path*\cczPqyfY.o:main.cpp:(.text+0x32): undefined reference to `tagData::tags[abi:cxx11]'
*Path*\cczPqyfY.o:main.cpp:(.text+0x46): undefined reference to `tagData::tags[abi:cxx11]'
collect2.exe: error: ld returned 1 exit status

I was looking for some info about how to declare static arrays in structs, but couldn't.我正在寻找一些关于如何在结构中声明 static arrays 的信息,但不能。 Can anybody show me an example or help me in another way?任何人都可以给我一个例子或以另一种方式帮助我吗?

PS I tried to compile this code with GCC version 8.1.0; PS我试图用GCC 8.1.0版编译这段代码;

struct tagData{
      static string tags[];
    };

This static class member must be defined in global scope , and not as a local variable in a function like main :这个 static class 成员必须在全局 scope中定义,而不是像 ZC1C425268E68394F11 中的main局部变量:

string tagData::tags[3];

And now, once the formalities are taken care of, you can manually access its class members, in main or any other function:现在,一旦手续办妥,您可以手动访问其 class 成员, main或任何其他 function:

int main(){
      tagData::tags[0] = "default";
      tagData::tags[1] = "player";
      tagData::tags[2] = "enemy";
      return 0;
    }

However, if the goal is to initialize the array there's an even better way.但是,如果目标是初始化数组,还有更好的方法。 Just initialize it as part of its definition:只需将其初始化为其定义的一部分:

string tagData::tags[3]={"default", "player", "enemy"};

Note: when defining static class member, you should always keep in mind the static initialization order fiasco .注意:在定义 static class 成员时,您应该始终牢记static 初始化顺序失败

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM