함수를 호출하는 하나의 메서드로 개체를 갖기를 원합니다. 그러나 모든 개체는 다른 함수를 호출해야합니다.함수를 전달하여 나중에 호출 할 수 있습니까?
이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
}
(분명히)이 코드는 작동하지 않습니다하지만 난 당신이 내가 달성하기 위해 노력하고 이해를 바랍니다 : 저는 예를 나타내는 무슨 뜻인지를 보여주기 위해 노력할 것입니다.
제조, 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