映射“RABBIT”字符串以调用新的“RABBIT”()

时间:2016-04-14 02:00:56

标签: c++ string oop object mapping

我必须用兔子,松鼠,狼和猎豹填充我的grid。我正在寻找字符串到类型对象的映射

populate("CHEETAH", 2);
populate("WOLF", 3);
populate("SQUIRREL", 10);
populate("RABBIT", 10);

目前,我有这个重复的代码,我想摆脱它。

CELL grid[GRIDHEIGHT][GRIDWIDTH];

void populate()
{
    int num_rabbits = 0, num_squirrels = 0, num_wolves = 0, num_cheetahs = 0;
    int random, randX, randY;
    srand((int)time(NULL));

    while (num_rabbits < 10)
    {
        randX = rand() % GRIDHEIGHT;
        randY = rand() % GRIDWIDTH;

        if (!(grid[randX][randY].Has_An_Animal()))
        {
            grid[randX][randY].animal = new RABBIT();
            num_rabbits++;
        }
    }

    while (num_squirrels < 10)
    {
        randX = rand() % GRIDHEIGHT;
        randY = rand() % GRIDWIDTH;

        if (!(grid[randX][randY].Has_An_Animal()))
        {
            grid[randX][randY].animal = new SQUIRREL();
            num_squirrels++;
        }
    }

    while (num_wolves < 3)
    {
        randX = rand() % GRIDHEIGHT;
        randY = rand() % GRIDWIDTH;

        if (!(grid[randX][randY].Has_An_Animal()))
        {
            grid[randX][randY].animal = new WOLF();
            num_wolves++;
        }
    }

    while (num_cheetahs < 2)
    {
        randX = rand() % GRIDHEIGHT;
        randY = rand() % GRIDWIDTH;

        if (!(grid[randX][randY].Has_An_Animal()))
        {
            grid[randX][randY].animal = new CHEETAH();
            num_cheetahs++;
        }
    }
}//end

1 个答案:

答案 0 :(得分:2)

我认为一个简单的方法就是实现模板功能。

template <typename T>
void populate(int maxPop) {
    int i = 0;

    while (i < maxPop)
    {
        randX = rand() % GRIDHEIGHT;
        randY = rand() % GRIDWIDTH;

        if (!(grid[randX][randY].Has_An_Animal()))
        {
            grid[randX][randY].animal = new T();
            i++;
        }
    }
}

然后简单地调用具有适当类型的函数:

populate<RABBIT>(10);