using namespace std;
class map
{
private:
float result= 0;
public:
void func_1();
void setres(float counter);
float getres();
};
void map::setres(float counter)
{
result= counter;
}
float map::getres()
{
return result;
}
void map::func_1()
{
float num_0=0, num_1=0, sum=0, i;
map run;
cout << run.getres() << " Result." << endl;
if(result != 0)
cout << "We already have a result saved and it's: " << run.getres() << endl;
else
{
cout << "Give me first number: ", cin >> num_0;
cout << "Give me second number: ", cin >> num_1;
sum= num_0+num_1;
cout << "Result is: " << sum << endl;
}
cout << "The program will save the result." << endl;
run.setres(sum);
cout << "The saved result is: " << run.getres() << "\nPress 1 to repeat the function and check\nif the result is saved." << endl;
cin >> i;
if(i==1)
run.func_1();
}
int main()
{
map go;
go.func_1();
return 0;
}
我不知道为什么不保存私有变量结果。我怎样才能让它工作。
然后我开始编译它工作正常,私有结果正在改变,但后来我重新打开函数,结果回到 0,我希望它成为最后一个结果。
示例:我放了 4 我放了 7 Sum 是 11 保存的结果是 11 然后我按 1 转到开始,结果又是 0,但我希望它是 11 而不是 0。
在函数中,您正在创建类型映射的局部变量
map run;
其数据成员结果已更改。即该函数不会更改调用该函数的对象的数据成员结果。
此外,例如在此代码片段中
cout << run.getres() << " Result." << endl;
if(result != 0)
您正在访问两个不同对象的数据成员结果。在第一个声明中
cout << run.getres() << " Result." << endl;
您run
在下一条语句中访问本地对象的数据成员
if(result != 0)
您正在访问go
为其调用成员函数的对象(在 main 中声明的对象)的数据成员结果。
所以去掉函数中的声明
map run;
而不是像这样的表达式,例如run.getres()
使用 justgetres()
或this->getres()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句