如何将输入变量传递给基于用户输入在许多地方调用的C++类方法

How do i pass input variable to a C++ class method invoked in many places based on user input?

本文关键字:输入 方调用 许多地 调用 类方法 C++ 用户 变量 于用户      更新时间:2023-10-16

我有一个文件中定义了多个独立的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中的代码放入每个函数中,具体取决于代码的复杂程度。