c++ - 无法将类中的输入函数与带参数的函数分开

标签 c++ constructor

在这个问题中无法分离输入函数

在这段代码中,我无法分离输入函数。但是,当我将输入放入 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 中的局部变量 abinput 函数的局部变量,它们一旦程序从函数返回,它们就不再存在,尽管它们与 main 中的变量 ab 同名.

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

你只需要在input中删除这一行:

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

顺便说一句:我不太清楚 swapValue 的用途,但基本上您似乎混淆了类成员和局部变量。

关于c++ - 无法将类中的输入函数与带参数的函数分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55808154/

相关文章:

python - 使用 Python 扩展 API 包装复杂的 C++ 类

java - 为什么在调用构造函数时将 int 隐式转换为 float 而不是 double?

c++ - 错误 LNK2019 未解析的外部符号 _main 在函数 "int __cdecl invoke_main(void)"(?invoke_main@@YAHXZ) 中引用

C++:打印列表

javascript - 如何从其构造函数中定义的 HTML 调用类方法?

javascript - 为什么 for...in 不打印对象的属性?

java - 需要编译 Java 的帮助(访问器、修改器、构造器)

c++ - 动态数组,动态构造函数

c++ - vtkSTLReader 只读取执行文件夹中的文件

c++ - 为什么这段代码会陷入死循环?