如何更高效地将用户输入直接传入类成员函数的参数?
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

