如何将输入变量传递给基于用户输入在许多地方调用的C++类方法
How do i pass input variable to a C++ class method invoked in many places based on user input?
我有一个文件中定义了多个独立的C样式函数,其中每个函数实例化一个类并使用某些参数调用该类的方法。
我需要从用户那里获取有关要调用的函数以及要在该方法中发送什么参数的输入。
基本上我的要求如下:
returnVal func1{
myClass obj;
obj.method(x,y);
}
returnVal func2{
myClass obj;
obj.method(x,y);
}
returnVal func3{
myClass obj;
obj.method(x,y);
}
//the value of y will need to change based on user selecting YES or NO
明显但乏味的方法是将
if(userChoice == YES){
obj.method(x,y);
}
else{
obj.method(x);
}
在每个函数中,但问题是我有太多这样的funcX,所以,我想知道是否有更简单的方法,通过使用宏或其他东西,但是宏在编译时被替换,所以我很困惑。
任何帮助,不胜感激。
如何使用开关/案例结构来确定要调用哪个函数以及使用什么值y
?
returnType (func*)(); // Create a function pointer and use that
switch(userInput){
case 0:
func = &func1;
y = 5;
case 1:
func = &func2;
y = 6;
}
为了简化每个函数中的代码,您可以使用包装器函数:
void callObjMethod(userInput, MyClass obj, x, y){
userInput == YES ? obj.method(x,y) : obj.method(x);
}
或者甚至只是将callObjMethod
中的代码放入每个函数中,具体取决于代码的复杂程度。
相关文章:
- 从类型std::函数传递变量失败,尽管调用方期望的类型完全相同
- 将错误返回给调用方而不是立即在 C++ 中抛出错误是否是一种好的做法
- 调用方如何知道 VARIANT 中何时有十进制?
- 从返回 std::optional of std::vector 的函数中获取结果到调用方
- "co_yield"是否可以在恢复协程时从调用方返回值?
- 使用 pybind11 调用 Python 函数时避免复制输入数据
- 如何使用从处理程序调度的最终回调将响应异步返回给调用方on_read?
- C++ 如何根据作为输入传递的参数调用一个构造函数或另一个构造函数?
- 使用多个输入向量中值的笛卡尔乘积调用 lambda
- 通过 C++ 中的指针将子对象值传递给被调用方类
- 是否允许调用方对我的 Builder 类使用任何指针类型(包括智能指针)?
- 如何启用使用另一个类的静态方法的模板函数的自动推导,从而消除冗长的调用方代码
- 具有不同类型的可选参数的调用方函数
- 程序在调用函数时跳过用户输入
- 使用 Spirit x3,如何控制在每个不同的输入上调用哪个解析器?
- 干净取消在输入/输出调用中被阻止的 std::线程
- 为什么在同一输入上调用std::getline()n次会产生第n个标记化
- 在unix平台上使用curses检测c++中的箭头键输入在调用系统命令后不起作用
- 如何根据输入值调用函数
- 用刷新输入从c++调用Matlab