c++ - 无法将类中的输入函数与带参数的函数分开
问题描述
在这个问题中不能分离输入功能
在这段代码中,我无法分离输入函数。但是,当我将输入放入 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;
}
局部变量a
和b
ininput
是函数的局部变量,input
一旦程序从函数返回,它们就不再存在,尽管它们与变量a
和b
in具有相同的名称main
。
这是编程教科书第一章中解释的最基本知识。
您只需删除以下行input
:
void test::input()
{
// delete this line: int a,b;
cin >> a >> b;
}
顺便说一句:我的目的swapValue
不是很清楚,但基本上你似乎混淆了类成员和局部变量。
推荐阅读
- javascript - 在 ag-grid 浮动过滤器中键入多个值
- python - (Tkinter)相同的代码 - 没有变化 - 当我运行它时会起作用然后不再起作用吗?绑定回车键功能
- javascript - React:以回调为道具连接 HOC
- python - 具有高斯先验的主持人给出 NaN
- google-analytics - PWA 渐进式 Web 应用中的 Google Analytics(分析)
- html - 我们如何使@media only max-width 不适用于更大的屏幕?
- node.js - 如何将我本地系统中的图像传递给表单数据并传递该表单数据以通过 Axios 执行发布请求
- python - Google Kickstart 2016 A 轮
- c# - 从事件触发器 oncreated (FileSystemWatcher) 加载的表单挂起。C#
- c# - 如何允许完整的 WPF 故事板动画