You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何更高效地将用户输入直接传入类成员函数的参数?

直接将用户输入传入类成员函数的简洁写法

Great question! You can absolutely cut out that intermediate num variable and make your code cleaner—here are two practical, straightforward ways to do this in C++:

方法1:重载类成员函数(推荐,更优雅)

The cleanest long-term fix is to add an overloaded version of your setNum method that directly reads from an input stream. This keeps input logic encapsulated in the class and makes your main code much more streamlined.

First, update your Customer class definition (in Customer.h):

#include <iostream>

class Customer {
private:
    int num;
public:
    // Original version for direct integer input
    void setNum(int n) {
        num = n;
    }

    // Overloaded version that reads from an input stream
    void setNum(std::istream& input) {
        input >> num;
    }

    int getNum() const {
        return num;
    }
};

Then your main code becomes super concise—no intermediate variable required:

#include <iostream>
#include "Customer.h"
using namespace std;

int main() {
    Customer object;
    cout << "Enter a number to be archived: ";
    object.setNum(cin); // Directly pass cin to the overloaded method
    cout << object.getNum();
}

方法2:不修改类的情况下使用Lambda表达式

If you can't or don't want to modify the Customer class, you can use a lambda expression to handle input inline when calling setNum:

#include <iostream>
#include "Customer.h"
using namespace std;

int main() {
    Customer object;
    cout << "Enter a number to be archived: ";
    // Use a lambda to read input and return the value directly as the parameter
    object.setNum([](){
        int temp;
        cin >> temp;
        return temp;
    }());
    cout << object.getNum();
}

This lambda acts as an inline mini-function that reads the input, stores it in a temporary local variable, and returns it immediately—all without cluttering your main scope with extra variables.

内容的提问来源于stack exchange,提问作者theNewGuy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 10:02:39