0

I have not used C++ in a long time. I'm trying to display some polymorphic behavior:

class func {
    public:
    virtual void print() = 0;
};

class func1 : public func {
    public:
    void print () { cout << "FUNC 1" << endl; };
};

class func2 : public func {
   public:
     void print () { cout << "FUNC 2" << endl; };
};


static map<string,func *> myMap;
static func1 f1 = func1 ();
static func2 f2 = func2 ();
myMap["func1"] = &f1;
myMap["func2"] = &f2;

So In my main function, when I call:

myMap["func1"]->print();
myMap["func2"]->print();

I would expect:

FUNC 1
FUNC 2

Not sure if this is the right way to do this. When I compile the code, it gives me this error:

test.cc:31: error: expected constructor, destructor, or type conversion before ‘=’ token
test.cc:32: error: expected constructor, destructor, or type conversion before ‘=’ token

Which refers to these lines:

myMap["func1"] = &f1;
myMap["func2"] = &f2;

Thank you.

4

1 回答 1

3

表达式语句,就像那些赋值语句一样,只能进入函数内部。

在 C++11 中,您可以使用大括号初始化来初始化静态映射:

static map<string,func *> myMap = {
    {"func1", &f1},
    {"func2", &f2}
};

如果你被困在过去,那么要么将它填充到一个函数中(也许是main,或者你在对地图做任何事情之前调用的东西),或者编写一个函数来返回一个填充的地图:

std::map<string,func*> make_map() {
    std::map<string,func*> map;
    map["func1"] = &f1;
    map["func2"] = &f2;
    return map;
}

static std::map<string,func *> myMap = make_map();

如果可能的话,一个更好的主意可能是避免非平凡的全局变量;他们常常带来痛苦的世界。

于 2014-07-28T17:09:16.930 回答