如何在C++中实现从一个函数到另一个函数的控制 如何在C++中实现从一个函数到另一个函数的控制?
基本上,我有一个函数a,它接受用户的输入并调用用户选择的函数。它可以通过使用switch-case构造调用所需的函数来完成,但是通过这种方式,控件将转到另一个函数,在执行之后,控件将返回到函数A,但我不希望这样。函数A应该在调用另一个函数时终止。您可以使用std::Function:如何在C++中实现从一个函数到另一个函数的控制 如何在C++中实现从一个函数到另一个函数的控制?,c++,function,return,C++,Function,Return,基本上,我有一个函数a,它接受用户的输入并调用用户选择的函数。它可以通过使用switch-case构造调用所需的函数来完成,但是通过这种方式,控件将转到另一个函数,在执行之后,控件将返回到函数A,但我不希望这样。函数A应该在调用另一个函数时终止。您可以使用std::Function: void B(); void C( int ); std::function<void()> A() { switch( userInput() ) { case 'B' : r
void B();
void C( int );
std::function<void()> A()
{
switch( userInput() ) {
case 'B' : return &B;
case 'C' : return std::bind( C, 123 );
}
return std::function<void()>{};
}
int main()
{
auto f = A();
if( f ) f();
}
这将在A终止后根据用户输入执行函数B或C123。您可以使用std::function:
void B();
void C( int );
std::function<void()> A()
{
switch( userInput() ) {
case 'B' : return &B;
case 'C' : return std::bind( C, 123 );
}
return std::function<void()>{};
}
int main()
{
auto f = A();
if( f ) f();
}
这将在A终止后根据用户输入执行函数B或C123。如果我理解正确,您可以执行以下操作 通过将用户输入传递给其他函数other_functions_hereint&user_input,您可以返回函数A,在这里您将根据用户输入处理开关箱/其他小功能 通过这种方式,您可以简单地在main中调用函数_A,如下所示 但是,在以这种方式编码时,您应该非常小心可能必须面对的异常。此外,调试也会很困难
#include <iostream>
int fun1() { return 1; }
int fun2() { return 2; }
int other_functions_here(int& user_input)
{
switch(user_input)
{
case 1: return fun1();
case 2: return fun2();
}
return -1;
}
int funcction_A()
{
int some_value;
std::cin >> some_value;
return other_functions_here(some_value);
}
int main()
{
int result = funcction_A();
(result != -1) ? std::cout << result :
std::cout << "Invalide user input" << std::endl;
return 0;
}
如果我理解正确,你可以做如下事情 通过将用户输入传递给其他函数other_functions_hereint&user_input,您可以返回函数A,在这里您将根据用户输入处理开关箱/其他小功能 通过这种方式,您可以简单地在main中调用函数_A,如下所示 但是,在以这种方式编码时,您应该非常小心可能必须面对的异常。此外,调试也会很困难
#include <iostream>
int fun1() { return 1; }
int fun2() { return 2; }
int other_functions_here(int& user_input)
{
switch(user_input)
{
case 1: return fun1();
case 2: return fun2();
}
return -1;
}
int funcction_A()
{
int some_value;
std::cin >> some_value;
return other_functions_here(some_value);
}
int main()
{
int result = funcction_A();
(result != -1) ? std::cout << result :
std::cout << "Invalide user input" << std::endl;
return 0;
}
您只需在调用另一个函数后从函数A返回。A应该是值类型的函数,您应该根据其返回值启动其他函数。否则它将成为一个派生函数,它应该使用并行处理,这样就失去了简单性。@FrançoisAndrieux可能会将您的评论作为答案发布-我不认为还有什么需要补充的:您只需在调用另一个函数后从函数a返回。a应该是值类型函数,您应该启动其他函数根据其返回值。否则,它将成为一个派生函数,应该使用并行处理,这样您就失去了简单性。@FrançoisAndrieux可能会将您的评论作为答案发布-我不认为还有什么需要补充的:如果我理解OP的要求,他们希望看到案例1:返回fun1;案例2:返回fun2;如果我理解OP的要求,他们希望看到案例1:返回fun1;案例2:返回fun2;这是OP想要的,我不想质疑他/她的要求。这是OP想要的,我不想质疑他/她的要求。这是OP想要的,我不想质疑他/她的要求