当我将值放入数组时变量被覆盖

时间:2018-11-27 19:17:50

标签: c++ c++11

该功能应该接受用户输入并将其放入地图对象中。宽度和长度被存储为Map中的变量,而id,x和y被存储在数组中。

[260,310]

这是将用户输入放入数组的函数:

void Game::createMap()
{
    Map map1;
    int width;
    int length;
    int id;
    int x;
    int y;
    string answer = "1";


    cout << "Enter a map width: " << endl;
    cin >> width;
    cout << "Enter a map length: " << endl;
    cin >> length;
    map1.setWidth(width);
    map1.setLength(length);


    while(answer != "2")
    {
        cout << "Would you like to add a player? 1) Yes 2) No" << endl;
        cin >> answer;
        switch (stoi(answer))
        {
            case 1:
                cout << "Choose player id: " << endl;
                cin >> id;
                cout << "Enter an x coordinate: " << endl;
                cin >> x;
                cout << "Enter a y coordinate: " << endl;
                cin >> y;
                map1.setPlayers(id, x, y, map1.getNumPlayers());

                break;


            case 2:
                break;
            default:
                cout << "Enter a valid input" << endl;
                break;
        }
    }
    mapVector.push_back(map1);
}

由于某种原因,在调用setPlayers函数之后,我的width和length变量被设置为从用户那里获得的id和x值。我不知道为什么要更改这些变量。好像当我在写数组时,它正在覆盖变量。

1 个答案:

答案 0 :(得分:0)

将行map1.setPlayers(id, x, y, map1.getNumPlayers()); 更改为map1.setPlayers( x, y, id , map1.getNumPlayers()); ,只需在调用函数setPlayers()时反转变量调用即可