你能根据整数是一个函数来调用函数吗?
这就是我的意思:
#include <iostream>
using namespace std;
int whichFunction;
int main()
{
cout << "Which function do you want to call?";
cin >> whichFunction;
function[whichFunction]();
//If you entered 1, it would call function1 - same with 2, 3
//or Hihihi (of course only when whichFunction would be a string)
}
void function1()
{
cout << "Function No. 1 was called!";
}
void function2()
{
cout << "Function No. 2 was called!";
}
void functionHihihi()
{
cout << "Function Hihihi was called!";
}
Run Code Online (Sandbox Code Playgroud)
我知道这不起作用,但我希望你明白这个想法.
有没有办法做这样的事情?
Rak*_*111 19
是的,有办法做到这一点.
//Array for the functions
std::array<std::function<void()>, 3> functions = { &function1, &function2, &function3 };
//You could also just set them manually
functions[0] = &function1;
functions[1] = &function2;
functions[2] = &function3;
Run Code Online (Sandbox Code Playgroud)
然后你可以将它用作普通数组:
functions[whichFunction](); //Calls function number 'whichFunction'
Run Code Online (Sandbox Code Playgroud)
请注意,所有功能都必须具有相同的签名.
如果std::function由于某种原因不想使用,可以使用函数指针.
Pet*_*ker 13
switch(whichFunction) {
case 1: function1(); break;
case 2: function2(); break;
case 3: function3(); break;
}
Run Code Online (Sandbox Code Playgroud)
使用指针函数是一件好事:
#include <iostream>
#include <string>
using namespace std;
void foo1(){cout << "Foo1 says hello!" << endl;}
void foo2(){cout << "Foo2 says hello!" << endl;}
void foo3(){cout << "Foo3 says hello!" << endl;}
void foo4(){cout << "Foo4 says hello!" << endl;}
int main()
{
system("color 1f");
int input;
cout << "Which function you wanna call: ";
cin >> input;
cout << endl;
void (*pFunc)() = NULL;
switch(input)
{
case 1:
pFunc = foo1;
break;
case 2:
pFunc = foo2;
break;
case 3:
pFunc = foo3;
break;
default:
cout << "No function available!" << endl;
}
if(NULL != pFunc) //avoiding usage of a NULL ptr
(*pFunc)();
cout << endl << endl << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)