I have a static member of a class of type map. but whenever I try to access it I always get an error. For example
// a.h
class a {
public:
static map<string, int>m;
a() {
}
~a() {
}
};
// a.cpp
a::m['ADD']=1;
this is the error I get = "Size of array has non-integer type 'const char[4]" I also get a weird error in the linker.
You need to define the map before you can use it:
std::map<std::string, int> a::m = std::map<std::string, int>{{"ADD", 1}};
This will initialize it to a map holding one element with key std::string("ADD")
and value 1
.
Note also, use double quotes for string literals.
Compiler error: You are using single-quotes when you probably meant to use double quotes.
Linker error: When defining static variables of a class, you also have to define them in a cpp file somewhere. Add the following line to your cpp file:
map<string, int> a::m;
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.