我想知道是否有一种“优雅”的方式可以根据用户输入选择运行特定的 (c++) 类成员函数。
例如,假设我们有一个这样的类:
class myClass
{
int foo;
myClass(int input) { foo = input;}
void runMyFunction()
{
if ( foo == 1)
{
function1();
}
else if (foo == 2)
{
function2();
}
}
void function1();
void function2();
};
我想做的是,如果用户在构造函数中指定 input=1
,那么当 runMyFunction( )
成员被调用,但如果用户在构造函数中指定了 input=2
,则应该调用 function2()
。
我的问题是,没有 if
语句是否有更优雅的方法?插入力是我不想让代码一遍又一遍地通过这个检查,因为我将在循环中使用这个调用。在这种情况下,是否有更优雅的方法来“设置”将在没有 if
语句的情况下调用哪个函数?谢谢。
最佳答案
是的,您可以使用命令模式。 你只需要设置一个函数方法指针数组。
std::vector<std::function<void()>> actionCommand =
{[](){}, // Zero based index.
[this](){this->function1();},
[this](){this->function2();}
};
void runMyFunction()
{
actionCommand[foo]();
// or
actionCommand.at(foo)(); // throws exception if foo is not in
// correct range.
}
关于c++ - 在C++中,如何在不使用if语句的情况下选择运行特定的成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30268507/