简体   繁体   中英

Declare static arrays in a struct right in C++

I tried to declare static array:

#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. 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;

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 :

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:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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