简体   繁体   中英

C++ initialize static map of objects

I am trying to create a map of static objects map<string, base*> , where base is derived by classes class1 and class2 . My map will store pointers to objects of type class1 and class2 .

After reading a few posts I decided to do this by creating a singleton with a static class function to initialize the map:

class A {  // singleton class
public:

static map<string, base*> create_map() {
map<string,base*> m;
m["1"]=new class1();
m["2"]=new class2();
};
static const map<string, base*> myMap;
};

int main() {    
const map<string,base*> A::myMap = A::create_map();
myMap["1"]->func();    
}

However this gives an error: myMap is not declared in this scope . Can somebody explain the singleton method and what I am doing wrong. How would this change if I have a separate header file ?
TIA.

EDIT: Changed the code to:

class A {  // singleton class
public:

static map<string, base*> create_map() {
map<string,base*> m;
m["1"]=new class1();
m["2"]=new class2();
return m;
};
static const map<string, base*> myMap;
};

const map<string,base*> A::myMap = A::create_map();
int main() {    

A::myMap["1"]->func();    
}

This still gives an error: passing const std::map<std::basic_string<char>, base*> as 'this' discards qualifiers.

myMap是A的成员,您需要相应地解决它。

A::myMap["1"]->func();    

You should add the line map<string, base*> A::myMap; after your class. You should also avoid the const declaration of your map object, and create_map() method was lacking of a return statement

class A {  // singleton class
public:

    static map<string, base*> create_map() {
        map<string,base*> m;
        m["1"] = new class1();
        m["2"] = new class2();

        return m;
    }

    static map<string, base*> myMap;
};

map<string, base*> A::myMap;

int main() {
    A::myMap = A::create_map();
    A::myMap["1"]->func();

    return 0;
}

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