class Dog
{
public:
void Update_Func(short i);
short (Dog::*pfunc)(short);
std::function<short(short)> ffunc;
public:
short goodMorning(short id);
short goodAfternoon(short id);
};
void Dog::Update_Func(short i)
{
switch (i)
{
case 1:
pfunc = &Dog::goodMorning;
ffunc = std::bind(&Dog::goodMorning, this, std::placeholders::_1);
break;
case 2:
pfunc = &Dog::goodAfternoon;
ffunc = std::bind(&Dog::goodAfternoon, this, std::placeholders::_1);
break;
}
}
short Dog::goodMorning(short id)
{
return id + 1;
}
short Dog::goodAfternoon(short id)
{
return id + 10;
}
int main()
{
Dog dog;
dog.Update_Func(1);
auto res = (dog.*(dog.pfunc))(10);
//auto res = (dog.*pfunc)(1); // 這樣是不行的,如果放在類外是可以的。
cout << res << endl;
short (Dog::*p)(short);
p = &Dog::goodAfternoon;
res = (dog.*p)(10); // 放在類外,這樣呼叫是可以的。
cout << res << endl;
/*用 function 應該是直接可以的*/
res = dog.ffunc(10);
cout << res << endl;
dog.Update_Func(2);
res = dog.ffunc(10);
cout << res << endl;
system("pause");
return EXIT_SUCCESS;
}
輸出:
11
20
11
20
如果成員函式指標放在類外,或用 function 繫結,goodMorning
和 goodAfternoon
兩個函式必須是 public 外部可訪問的。 如果是類內部成員函式指標,goodMorning
和 goodAfternoon
這兩個函式可以是私有的。