Reputation:
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?
P.S. I tried to compile this code with GCC version 8.1.0;
Upvotes: 1
Views: 71
Reputation: 118300
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.
Upvotes: 3