0
#include <map>

class ICommand
{
public:
    virtual double execute(double, double);
    ~ICommand();
};
class Add: public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a + b;
    }
    double operator()(double a, double b){
        return a + b;
    }

};
class Sub : public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a - b;
    }
    double operator()(double a, double b) {
        return a - b;
    }
};
class Mul : public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a * b;
    }
    double operator()(double a, double b) {
        return a * b;
    }
};
class Div : public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a / b;
    }
    double operator()(double a, double b) {
        return a / b;
    }
};

class RequestHundler
{
    std::map<int, ICommand*> commands;
    Add* add;
    Sub* sub;
    Mul* mul;
    Div* div;
public:
    RequestHundler()
    {
        commands[1] = add;
        commands[2] = sub;
        commands[3] = mul;
        commands[4] = div;
    }
    double HandleRequest(int action, double a, double b)
    {
        ICommand* command = commands[action];
        return  command->execute(a, b);
    }
};


int main(double argc, char* argv[])
{
    RequestHundler* handler = new RequestHundler();
    double result = handler->HandleRequest(2, 4, 6);
    return 0;
}

我在 command->execute(a, b); 中有访问冲突;,因为map只包含空指针,填充后。存储和填充地图的正确方法是什么?我认为我应该使用工厂来创建类,但即使在这种情况下我也必须填充地图,而且我不太想使用全局变量来保存地图。也许对这段代码有什么好主意?

4

0 回答 0