我想用一個方法調用一個函數的對象(但每個對象應該有一個不同的函數來調用)。我會試着告訴你我通過展示一個例子的意思是:你可以傳遞一個函數,以便稍後調用它嗎?
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
}
此代碼(顯然)不工作,但我希望你明白我試圖完成。
MFG,TPRammus
你會想要使用[std :: function](http://en.cppreference.com/w/cpp/utility/functional/function)。 –
要傳遞給類的函數的簽名是相同還是應該接受'int(int,int)','double(double)'和'void(int)'...? – NathanOliver
你也可以使用[函數指針](http://www.cprogramming.com/tutorial/function-pointers.html)。 – Gavin