从Vector而不是Array调用类函数
Calling a class function from a Vector instead of an Array
我目前正在研究一种方法,从一个文件中加载一堆不同的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向量不是更好吗?
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 当使用Char Array和= Operator启动字符串时,该功能被调用
- 节点.JS,C++模块:为什么当我尝试调用本地的长度方法时出现段错误<Array>?
- 从 PHP 调用 C++ 应用程序 - 输出显示"Array"
- 从Vector而不是Array调用类函数
- 对std::array中的元素调用用户定义的构造函数
- 调用matrix.array()后将矩阵保存为数组格式
- 在CUDA内核内存调用中使用array[i][j]
- 从c# Array MarshalAs Problems中调用c++