Look at this very basic c++ class:
class MyClass {
public:
static std::map<int, std::string> test;
void method1()
{
std::cout << test[1] << std::endl;
}
};
int main()
{
MyClass::test[1]="test";
return 0;
}
As you can see, this very basic class contains a static field. But when i am trying to access it, i get this compiler error:
undefined reference to `MyClass::test[abi:cxx11]'
In order to make it work, i have tried to create a static method and declare my static field inside this method. It works, but it looks ugly. I want to understand why my first code does not work and why this second code works...
class MyClass {
public:
static std::map<int, std::string> get_test()
{
static std::map<int, std::string> test;
return test;
}
void method1()
{
std::cout << get_test()[1] << std::endl;
}
};
int main()
{
MyClass::get_test()[1]="test";
return 0;
}
Thanks