从Vector而不是Array调用类函数

Calling a class function from a Vector instead of an Array

本文关键字:Array 调用 类函数 Vector      更新时间:2023-10-16

我目前正在研究一种方法,从一个文件中加载一堆不同的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 programn";
    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 inputn"; break;
    }
}
Creatures[MAX_NPCS].CleanUp(Creatures);
cout << "Exitingn";
system("PAUSE");
return 0;
}

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

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

Creatures[1].Attack(Creatures);

当然,当我这样调用它们时,值不会正确返回,我通常会得到一个错误。此外,我不知道当前地图将加载多少NPC(如果有的话)。

如有任何帮助,我们将不胜感激。我意识到我是编程的新手,尤其是Vectors。如果需要我的功能代码,我会很乐意发布。

您可以创建一个向量,并在其中拥有第一个元素,以便能够调用InitCreatures函数(您也可以稍后覆盖第一个生物)。

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

我假设在类中,您有通过引用传递的参数。

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

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