首页 > 解决方案 > 无法将类中的输入函数与带参数的函数分开

问题描述

在这个问题中不能分离输入功能

在这段代码中,我无法分离输入函数。但是,当我将输入放入 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;
}

标签: c++constructor

解决方案


void test::input()
{
    int a,b;   // these are local variables
    cin>>a>>b;
}

局部变量abininput是函数的局部变量,input一旦程序从函数返回,它们就不再存在,尽管它们与变量abin具有相同的名称main

这是编程教科书第一章中解释的最基本知识。

您只需删除以下行input

void test::input()
{
    // delete this line:   int a,b;
    cin >> a >> b;
}

顺便说一句:我的目的swapValue不是很清楚,但基本上你似乎混淆了类成员和局部变量。


推荐阅读