我有一个子程序 Map build(Map the_map)
被调用来更新我的变量 new_map
并且 map 正在子程序内部更新但是当它返回时它返回相同的 map 未更新,
笔记:
我在方法中使用 cout
语句进行了测试,并且在方法返回到开关之后...
这是我的代码片段:
1 结构细节
2 和调用子程序的时刻
3、子程序代码
结构
struct MapItem {
char type = 'E';
};
struct Map {
int size = 0;
MapItem *items;
};
在 switch 中调用子程序(如果用户选择构建选项)在 map 上构建
case BUILD:
new_map = build(new_map);
break;
子程序
Map build (Map the_map) {
char building_code;
int coordinate_x;
int coordinate_y;
int build_location;
cout << "Enter x and y coordinate: ";
cin >> coordinate_x;
cin >> coordinate_y;
build_location = (coordinate_x+(coordinate_y*the_map.size));
cout << "Enter a building code: ";
cin >> building_code;
the_map.items[build_location].type = building_code;
return the_map;
}
最佳答案
尝试通过引用传递 map 。
像这样:
void build (Map& the_map) {
char building_code;
int coordinate_x;
int coordinate_y;
int build_location;
cout << "Enter x and y coordinate: ";
cin >> coordinate_x;
cin >> coordinate_y;
build_location = (coordinate_x+(coordinate_y*the_map.size));
cout << "Enter a building code: ";
cin >> building_code;
the_map.items[build_location].type = building_code;
}
和
case BUILD:
build(new_map);
break;
当您通过引用传递时,您可以直接更改变量(即映射)并避免所有复制的复杂性。
顺便说一句:我假设您已经在代码中的其他地方为 MapItems 保留了内存,但您可能需要在构建函数内部进行一些范围检查,这样您就不会在分配的内存之外进行写入。
如果您已正确初始化,您的初始代码应该没问题。我这样试过:
Map build(Map the_map) {
char building_code;
int coordinate_x;
int coordinate_y;
int build_location;
cout << "Enter x and y coordinate: ";
cin >> coordinate_x;
cin >> coordinate_y;
build_location = (coordinate_x + (coordinate_y*the_map.size));
// Range check
if ((build_location >= (the_map.size*the_map.size)) || (build_location < 0))
{
cout << "Invalid" << endl;
return the_map;
}
cout << "Enter a building code: ";
cin >> building_code;
the_map.items[build_location].type = building_code;
return the_map;
}
int main()
{
// Just a const so that map size can be change here
const int mapSize = 3;
// Create the map
Map new_map;
// Initialize map size
new_map.size = mapSize;
// Allocate memory for the MapItems
new_map.items = new MapItem[mapSize * mapSize];
// Do some simple test...
for (int i = 0; i < mapSize * mapSize; i++) cout << new_map.items[i].type << " ";
cout << endl;
for (int j = 0; j < 3; j++)
{
new_map = build(new_map);
for (int i = 0; i < mapSize * mapSize; i++) cout << new_map.items[i].type << " ";
cout << endl;
}
// Deallocate memory
delete[] new_map.items;
return 0;
}
E E E E E E E E E
Enter x and y coordinate: 2 0
Enter a building code: Y
E E Y E E E E E E
Enter x and y coordinate: 0 2
Enter a building code: Z
E E Y E E E Z E E
Enter x and y coordinate: 2 2
Enter a building code: P
E E Y E E E Z E P
但我会推荐传递引用。
关于c++结构和方法,未正确返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707242/