在map中存储派生类的成员函数指针

时间:2010-12-26 10:22:37

标签: c++ function-pointers

我正在尝试为两个类Circle实现工厂,Square都继承自Shape。

class Shape {
public: 
    virtual static
    Shape * getInstance() = 0;

};

class Circle : public Shape {        
public:
    static const std::string type;

    Shape * getInstance() {
        return new Circle;
    }
};
const std::string Circle::type = "Circle";

class Square : public Shape {        
public:
    static const std::string type;

    Shape * getInstance() {
        return new Square;
    }
};
const std::string Square::type = "Square"; 

我现在想创建一个带有键作为形状类型(字符串)的映射,并将值作为指向相应派生类的getInstance()的函数指针。有可能吗?

谢谢, 基兰

3 个答案:

答案 0 :(得分:2)

好的,我弄错了。

1)不应该声明 - virtual static Shape * getInstance()= 0; - 在Shape类中。

2)getInstance()在所有其他类中应该是静态的。

这是完整的实施

class Shape {
public:

    virtual
    std::string getType() = 0;

};

class Circle : public Shape {

public:
static const std::string type;
    Circle() {

    }

    std::string getType() {
        return type;
    }

    static
    Shape * getInstance() {
        return new Circle;
    }
};
const std::string Circle::type = "Circle";

class Square : public Shape {

public:
static const std::string type;
    Square() {
    }

    std::string getType() {
        return type;
    }

    static
    Shape * getInstance() {
        return new Square;
    }
};
const std::string Square::type = "Square";

class Triangle : public Shape {

public:
static const std::string type;
    Triangle() {
    }

    std::string getType() {
        return type;
    }

    static
    Shape * getInstance() {
        return new Triangle;
    }
};
const std::string Triangle::type = "Triangle";


typedef Shape * (*getShape)();
typedef std::map<std::string, getShape > factoryMap;

class ShapeFactory {
public:
    static factoryMap shapes;
    Shape * getInstance(const std::string & type){
        factoryMap::iterator itr = shapes.find(type);
        if (itr != shapes.end()){
            return (*itr->second)();
        }
        return NULL;
    }

};

factoryMap ShapeFactory::shapes;

class ShapeFactoryInitializer {
    static ShapeFactoryInitializer si;
public:

    ShapeFactoryInitializer() {
        ShapeFactory::shapes[Circle::type] = &Circle::getInstance;
        ShapeFactory::shapes[Square::type] = &Square::getInstance;
        ShapeFactory::shapes[Triangle::type] = &Triangle::getInstance;
    }

};

ShapeFactoryInitializer ShapeFactoryInitializer::si;

答案 1 :(得分:0)

虽然与您的问题没有多大关系,但如果您对现代C ++设计(工厂,智能指针等)感兴趣,您可以查看这本书:

http://www.amazon.co.uk/Modern-Design-Applied-Generic-Patterns/dp/0201704315/ref=sr_1_20?s=books&ie=UTF8&qid=1293359949&sr=1-20

谈论工厂,如何设计工厂等等。

PS:我不是这本书的作者,也没有给我任何回复的答案: - )

答案 2 :(得分:0)

将代码的最后一行更改为ShapeFactoryInitializer ShapeFactoryInitializer::si;,然后它将通过编译。

相关问题