我的主要程序是生成一个随机数,以创建二维数组中对象的移动并跟踪它。
我的一个函数void current_row(int row){position = row};
跟踪对象的当前行。
因为变量不是全局变量。我发现调用当前位置并将其更新到下一个移动时出现问题。这是其他功能的样子:
void movement (){
int row;
row = current_row();
/*
* Here is the problem i'm having. This may well be
* a third function which has the same information
* as my first function. But still how do I access
* once without modifying it and access it
* again to update it?
*/
// call another function that creates new row.
// update that info to the row
}
我是c ++的新手。
答案 0 :(得分:1)
使用实例变量来跟踪它。这就是为什么存在实例变量的原因:在函数调用之间保持它们的值。
答案 1 :(得分:0)
如果它是一个OOP环境(如C ++标签所暗示的),某些类应该将 int row 声明为类成员(包括getter和setter作为方法)。
另一个选项是在程序的 main()部分的头部声明变量,并使用row作为函数参数调用函数。
无效移动(int行) {
}
如果您打算更改参数,可以考虑通过引用传递参数,否则最好在函数参数声明中声明它为const。如果部分答案听起来不熟悉,我建议您阅读: What's the difference between passing by reference vs. passing by value?