【发布时间】:2014-02-03 07:38:07
【问题描述】:
这刚刚变成了一场火焰战争。如果我不明白,我会再问这个问题。
值在函数内部发生变化,但一旦函数结束,值就会恢复到最初设置的值。
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
我知道数组是通过引用传递的,所以我认为这会按原样工作。但显然我没有正确理解某些东西。目前仍在学习语言。 也许我没有正确传递数组?
【问题讨论】:
-
您对输入/输出有什么特别的问题/期望?详细说明(编辑您的问题!!),目前还不清楚您的要求是什么!
-
foo::changebar中的bar确实是this->bar。所以应该改变价值观。与struct problem的声明位置无关。 -
好吧.. 删除了我的答案.. 一些白痴无缘无故地决定投反对票.. 无论如何,只要看看 ideone 链接。您的代码没有任何问题。 bar 的值确实发生了变化。
-
好的,肯定是其他地方出了点问题。感谢您的帮助。