// 函数指针的使用
#include <iostream>
using namespace std;
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
enum BOOL
{ FALSE, TRUE };
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
class Dog
{
public:
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
void Speak() const
{ cout << "woof!\n"; }
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
void Move() const
{ cout << "Walking to heel
\n"; }
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
void Eat() const
{ cout << "Gobbling food
\n"; }
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
void Growl() const
{ cout << "Grrrrr\n"; }
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
void Whimper() const
{ cout << "Whining noises
\n"; }
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
void RollOver() const
{ cout << "Rolling over
\n"; }
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
void PlayDead() const
{ cout << "Is this the end of Little Caeser? \n"; }
};
![](/Images/OutliningIndicators/None.gif)
typedef void (Dog::*PDF) () const;
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
int main(int argc, char* argv[])
{
const int MaxFuncs = 7;
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
PDF DogFunctions[MaxFuncs] =
{
&Dog::Speak,
&Dog::Move,
&Dog::Eat,
&Dog::Growl,
&Dog::Whimper,
&Dog::RollOver,
&Dog::PlayDead
};
Dog* pDog = 0;
int member;
BOOL fQuit = FALSE;
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
while (!fQuit)
{
cout << "(0) Quit (1) Speak (2) Move (3) Eat (4) Growl";
cout << " (5)Whimper (6) Roll Over (7) Play Dead:";
cin >> member;
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if (member == 0)
{
fQuit = TRUE;
break;
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
else
{
pDog = new Dog;
(pDog->*DogFunctions[member - 1]) ();
delete pDog;
}
}
return 0;
}
![](/Images/OutliningIndicators/None.gif)
这个代码里数组定义原来是
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
PDF DogFunctions[MaxFuncs] =
{
Dog::Speak,
Dog::Move,
Dog::Eat,
Dog::Growl,
Dog::Whimper,
Dog::RollOver,
Dog::PlayDead
};
![](/Images/OutliningIndicators/None.gif)
在 gcc 下编译不能通过, 改成加一个 & 就通过了。
引用书上的一段解释:
函数指针不需要取消对它的引用。因此,如果 pFunc 是一个整参数、返回 long 型变量的函数指针,而且程序给 pFunc 分配了匹配的函数,程序用 pFunc(x); 或 (*pFunc)(x) 都可以调用该函数。 两种格式效果是一样的,前者比后者简单。用 vc 编译则加不加 & 都可以通过。
看来是 vc 和 gcc 对 c++ 标准支持的程度不同导致的。
要/不要对类的特定对象调用函数成员指针。
使用 typedef 提高函数成员指针的声明的可读性。
如果有更简单的解决办法就不要使用函数成员指针。