在这个问题中无法分离输入函数
在这段代码中,我无法分离输入函数。但是,当我将输入放入 int main() 时,它会显示正确的解决方案。我的代码有什么问题?
#include<iostream>
using namespace std;
class test
{
int a,b;
public:
void input();
void swapValue(int value1, int value2);
};
void test::input()
{
cin>>a>>b;
}
void test::swapValue(int value1, int value2)
{
cout << "Swap value in function" << endl;
int temp = value1;
value1 = value2;
value2 = temp;
cout << "value 1: " << value1 << endl;
cout << "value 2: " << value2 << endl;
}
int main()
{
int a,b;
test s1;
s1.input();
cout << "===============================" << endl;
cout << "After the function call" << endl;
s1.swapValue(a, b);
system("pause");
return 0;
}
最佳答案
void test::input()
{
int a,b; // these are local variables
cin>>a>>b;
}
input
中的局部变量 a
和 b
是 input
函数的局部变量,它们一旦程序从函数返回,它们就不再存在,尽管它们与 main
中的变量 a
和 b
同名.
这是编程教科书第一章中解释的最基本的知识。
你只需要在input
中删除这一行:
void test::input()
{
// delete this line: int a,b;
cin >> a >> b;
}
顺便说一句:我不太清楚 swapValue
的用途,但基本上您似乎混淆了类成员和局部变量。
关于c++ - 无法将类中的输入函数与带参数的函数分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55808154/