从Vector而不是Array调用类函数

时间:2012-03-27 20:57:45

标签: c++ arrays class function vector

我目前正致力于从文件中加载一堆不同的NPC并将其加载到我的游戏中。我有一切正常使用数组,但我想将其更改为使用向量,因为我可以更改大小,以防我需要更多的NPC而不是数组中的可用空间,所以我不只是有一个大多数空数组我目前不需要很多NPC。请注意,以下代码来自测试程序,而不是我的实际编程。我做到了所以我不小心搞乱整个项目。

int main()
{
char input;
bool Running = true;
NPC Creatures[MAX_NPCS];

//InitCreatures loads the X, Y and Type from the file. I know with vectors I have to
//resize it as I go along, Which would be included in the function.
if(Creatures[MAX_NPCS].InitCreatures(Creatures) == false)
{
    Creatures[MAX_NPCS].CleanUp(Creatures);
    return 0;
}

while(Running == true)
{
    cout << "(C)heck an NPC, (A)ttack and NPC or (E)xit the program\n";
    cin >> input;
    switch(input)
    {
        case 'C': Creatures[MAX_NPCS].Check(Creatures); break;
        case 'c': Creatures[MAX_NPCS].Check(Creatures); break;
        //The Check function just shows the X, Y and Type of the NPC
        case 'A': Creatures[MAX_NPCS].Attack(Creatures); break;
        case 'a': Creatures[MAX_NPCS].Attack(Creatures); break;
        //Attack shows X, Y and type and then removes that NPC from the array.
        case 'E': Running = false; break;
        case 'e': Running = false; break;
        default: cout << "That was not a valid input\n"; break;
    }
}

Creatures[MAX_NPCS].CleanUp(Creatures);
cout << "Exiting\n";
system("PAUSE");
return 0;
}

我遇到的唯一问题是让Main从向量中运行NPC类函数而不是像现在这样使用数组。我可以很容易地改变我正在调用的函数中接受向量并正确处理它的其他东西。

当尝试使用向量来运行函数时,我只能在我有这样的东西时调用它们:

Creatures[1].Attack(Creatures);

当然,当我这样称呼它们时,值不能正确返回,我通常会收到错误。除此之外,我不知道当前地图会加载多少个NPC,如果有的话。

任何有关此的帮助将不胜感激。我发现在编程方面我是一个新手,尤其是涉及到Vector时。如果需要我的功能代码,我很乐意发布它。

1 个答案:

答案 0 :(得分:0)

你可以创建一个向量并让第一个元素能够调用InitCreatures函数(你也可以在以后覆盖第一个生物)。

vector<NPC> Creatures(1);
Creatures[0].InitCreatures(Creatures);

我假设在课堂上你有参考传递的参数。

bool InitCreatures(vector<NPC>& x) { ... }

但是既然你把生物作为参数给你拥有的每一个函数(你需要检查或攻击它吗?) - 有一个类来保存NPC向量会不会更好?