你能根据整数是一个函数来调用函数吗?
这就是我的意思:
#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 …Run Code Online (Sandbox Code Playgroud) 我希望对象有一个调用函数的方法(但每个对象应该有一个不同的函数来调用).我将通过展示一个例子来向您展示我的意思:
class Human
{
public:
void setMyFunction(void func); // specify which function to call
void callMyFunction(); // Call the specified function
};
void Human::setMyFunction(void func) // ''
{
myFunction = func;
}
void Human::callMyFunction() // ''
{
myFunction();
}
void someRandomFunction() // A random function
{
// Some random code
}
int main()
{
Human Lisa; // Create Object
Lisa.setMyFunction(); // Set the function for that object
Lisa.callMyFunction(); // Call the function specified earlier
}
Run Code Online (Sandbox Code Playgroud)
这个代码(显然)不起作用,但我希望你理解我想要完成的事情.
MfG,TPRammus