c++ - STL映射和纯虚基类

标签 c++ stl virtual abstract-base-class

很久没有用过C++了。我正在尝试显示一些多态行为:

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;

所以在我的主函数中,当我调用时:

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

我希望:

FUNC 1
FUNC 2

不确定这是否是正确的方法。当我编译代码时,它给了我这个错误:

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

这是指这些行:

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

谢谢。

最佳答案

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

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

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

如果你停留在过去,那么要么在一个函数中填充它(可能是main,或者你在对 map 做任何事情之前调用的东西),要么写一个函数来返回一个填充的 map :

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();

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

关于c++ - STL映射和纯虚基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25000397/

相关文章:

STL - 如何从 numpy-STL 网格中提取顶点?

c++ - 使用抽象类实现派生类的元素栈

C++ 继承 : does lack of virtual destructor lead to memory leak?

c++ - D3D 线绘制分成三角形 - 它几乎可以工作,但需要提示

c++ - 整数<->指针转换何时真正正确?

c++ - 适用于 iOS 的 QtCreator : How to deploy a dylib shared library with my application

c++ - 找到数字属于哪个部分的快速方法是什么(在 C++ 中使用 vector )?

c++ - 将 std::vector<T> move 到 T*

linux-kernel - 在现代 Linux(2.6.30+ 内核)系统上可以创建(和安装)多少个循环设备?

c++ - QTcpSocket - 如何发送两个数字