这刚刚变成了一场火焰战。如果我不明白,我会在以后再问这个问题。
在函数内部更改值,但一旦函数结束,值将返回到最初设置的值。
class inventory
{
private:
struct instock {
double everything[4]; //Gets set to 0-3. Then user changes values.
};
public:
instock stock;
void changegas(double userinput);
void stocking(); //populates the array
void output(); //outputs the array
};
void inventory::stocking(){
for(int i=0; i<4; i++){
stock.everything[i]=i;
}
}
void inventory::changegas(double input){
double a;
a = input;
stock.everything[0] += a;
std::cout << "Gas remaining: " << stock.everything[0];
}
void inventory::output(){
std::cout << std::endl;
for(int i=0; i<4; i++){
std::cout << stock.everything[i];
}
}
void inventory::changegas(double input){
double a;
a = input;
stock.everything[0] += a;
std::cout << "Gas remaining: " << stock.everything[0];
}
我该怎么做才能让这个函数永久地改变存储在一切中的数组的值?
int main()
{
backroom.stocking();
int choice;
cout << "What would you like to change? \n1.)Gas\n2.)Tires\n3.)Soda\n4.)Snacks"<<endl;
cin >> choice;
menu(choice, backroom);
backroom.output();
return 0;
}
void menu(int zed, inventory a){
int z = zed;
int c = 0;
switch (z){//start switch
case 1:
cout << "Enter the amount of Gas you want to change: ";
cin >> c;
a.changegas(c);
break;
case 2:
cout << "Enter the amount of Tires you want to change: ";
cin >> c;
a.changetires(c);
break;
case 3:
cout << "Enter the amount of Soda you want to change: ";
cin >> c;
a.changesoda(c);
break;
case 4:
cout << "Enter the amount of Snacks you want to change: ";
cin >> c;
a.changesnacks(c);
break;
break;
}//endswitch
}// end funct
我知道数组是通过引用传递的,所以我认为这样可以正常工作。但显然我并没有正确理解。目前仍在学习语言。 也许我没有正确地传递数组?
答案 0 :(得分:2)
你按价值通过了后台。您需要更改menu()
以接收库存参考或库存指针,最好是前者。这是因为当您按值传递类对象时,整个对象将被复制到被调用函数的本地新实例,并且对该实例所做的任何更改都不会影响原始副本。
这应该有效:
void menu(int zed, inventory& a) {
int z = zed; //you don't need this by the way
int c = 0;
switch (z){//start switch
case 1:
cout << "Enter the amount of Gas you want to change: ";
cin >> c;
a.changegas(c);
break;
case 2:
cout << "Enter the amount of Tires you want to change: ";
cin >> c;
a.changetires(c);
break;
case 3:
cout << "Enter the amount of Soda you want to change: ";
cin >> c;
a.changesoda(c);
break;
case 4:
cout << "Enter the amount of Snacks you want to change: ";
cin >> c;
a.changesnacks(c);
break;
}
}