从 C++ 中的 switch case 返回二维数组
我正在 cocos2dx 中编写一个游戏,并且我正在尝试重构一个被调用几次的方法。我想从车辆类型枚举返回一个二维数组
我怎样才能得到像下面这样的东西工作?
int Vehicle::getVehicle(VehicleTypes vehicletypes)
{
int vehicle[8][8] = {0};
switch (vehicleType) {
case Car:
// --- ARRAY 1 ------
vehicle = {
{ 0,0,0,0,0,0,0,0 },
{ 0,0,1,2,5,8,0,0 },
{ 0,0,5,3,4,5,0,0 },
{ 0,0,0,6,0,7,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
};
break;
case Bus:
{
// --- ARRAY 2 ------
Vehicle = {
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,1,2,0,0 },
{ 0,0,3,4,5,0,0,0 },
{ 0,0,6,8,7,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
};
break;
}
default:
break;
}
return vehicle;
}
谢谢
I'm writing a game in cocos2dx, and i'm trying to refactor a method thats gets called a few times. I want to return a two dimensional array from an enum of vehicletype
How can i get something like the following to work??
int Vehicle::getVehicle(VehicleTypes vehicletypes)
{
int vehicle[8][8] = {0};
switch (vehicleType) {
case Car:
// --- ARRAY 1 ------
vehicle = {
{ 0,0,0,0,0,0,0,0 },
{ 0,0,1,2,5,8,0,0 },
{ 0,0,5,3,4,5,0,0 },
{ 0,0,0,6,0,7,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
};
break;
case Bus:
{
// --- ARRAY 2 ------
Vehicle = {
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,1,2,0,0 },
{ 0,0,3,4,5,0,0,0 },
{ 0,0,6,8,7,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
};
break;
}
default:
break;
}
return vehicle;
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
演示:http://ideone.com/i1Tc2
Demo: http://ideone.com/i1Tc2
你为什么使用数组?您应该使用 STL 容器之一,例如向量。不管怎样,C++ 中的 2D int 数组基本上是一个指向 int 指针的指针。函数的调用者需要在堆或堆栈上提供一个分配的二维数组并将其作为输入/输出参数传递,或者让“被调用者”(此函数)在堆上分配一个二维数组并将其传递回函数呼叫者。如果是后一种情况,那么调用者现在负责释放内存。
Why are you using arrays? You should use one of the STL containers such as a vector. Either way, a 2D int array in C++ is basically a pointer to a pointer of int's. Either the caller of the function needs to supply an allocated 2D array on the heap or stack and pass it as a in/out argument or have the "callee" (this function) allocate a 2D array on the heap and pass it back to the caller. If it's the latter case, then the caller is now responsible for deallocating the memory.