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

标签 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"; 

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

谢谢, 基兰

最佳答案

好吧,我搞错了。

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;

关于c++ - 在map中存储派生类的成员函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4533482/

相关文章:

c++ - 如何创建一个MFC CSliderCtrl?

c++ - 将库放入 Linux 中的 exe 文件夹中

c++ - PhysX.sln 无法编译(PhysX 3.4)

c++ - 通过标准平均 C++ 模糊图像

c++ - 为什么我的列表框没有调整大小? (动态调整对话框组件的大小)

c++ - 在函数内删除分配的数组 vs 在 main 中

c - 我的程序运行正常,但收到警告

fortran - Fortran中如何指向类方法?

Python:如何创建带有设置参数的函数指针?

c++ - 使用带闭包的 lambda 回调