C ++ Cant Change Object的变量

时间:2017-10-30 09:36:56

标签: class object

class ship {
public:
    int location;
    int length;
};

void createship(ship ship1, int gridsize) {             //function to set ship1's length and location
    srand(time(NULL));
    ship1.length = (int)((rand()) % gridsize) / 4 + 1;
    ship1.location = (int)(rand()) % gridsize;
}

void insertship(ship ship1, vector <char> grid) {           //insert ship into grid, change grid's elements from 'e' to 'f'
    for (int temp2= 0; temp2 < ship1.length; temp2++) {
        grid[ship1.location + temp2] = 'f';
    }
}

int main()
{
    int gridsize;
    cout << "Gridsize: ";
    cin >> gridsize;
    cout << "\n";
    vector <char> grid(gridsize, 'e');
    for (int temp3 = 0; temp3 < grid.size(); temp3++) {         //cout vector grid
        cout << grid[temp3];
    }
    cout << "\n";
    ship* ship1 = new ship();                               //create ship1
    createship(*ship1, gridsize);
    insertship(*ship1, grid);
    cout << (*ship1).length << "\n";
    cout << (*ship1).location << "\n";
    for (int temp4 = 0; temp4 < grid.size(); temp4++) {         //cout vector grid again (with ship)
        cout << grid[temp4];
    }
    return 0;
}

我的ship1.length和ship1.location始终保持为零,即使createship()函数应该将其更改为随机数字?我犯了什么错误?

只是在下面添加更多单词,因为stackexchange不允许我在我的问题中添加大部分代码

2 个答案:

答案 0 :(得分:0)

您按值ship传递,因此参数createship获取的是原始对象的副本,更改它不会更改原始对象。

将引用/指针传递给ship,然后更改参数将更改原始对象。

或者更好,使用constructor

答案 1 :(得分:0)

您通过值传递参数,该参数将创建和更改函数中的局部变量而不是源变量。 您应该通过引用传递参数。

void createship(ship &ship1, int gridsize) {            
  srand(time(NULL));
  ship1.length = (int)((rand()) % gridsize) / 4 + 1;
  ship1.location = (int)(rand()) % gridsize;
}

无论如何,在你的情况下,使用成员函数可能是一个更好的解决方案。

class ship {
public:
  int location;
  int length;
  void createship(int gridsize) { 
    srand(time(NULL));
    this->length = (int)((rand()) % gridsize) / 4 + 1;
    this->location = (int)(rand()) % gridsize;
  }
};

呼叫:

ship1->createship(100);