酸菜猪蹄的程序人生
木下编程屯屯烫烫
下面是例子,如果对C的函数指针有一定体会的话,相信这个例子很容易就看明白了。(其实是一样的。)

#include <iostream>
#include <string>
using namespace std;
class CPerson;
typedef void (CPerson::*PF)(const CPerson&);
class CPerson
{
private:
   string name;
public:
   CPerson(const string& name);
   void Slap(const CPerson& p);
   void Kick(const CPerson& p);
};

CPerson::CPerson(const string& name)
{
   this->name = name;
}
void CPerson::Slap(const CPerson& p)
{
   cout << this->name << " slap " << p.name << endl;
}
void CPerson::Kick(const CPerson& p)
{
   cout << this->name << " kick " << p.name << endl;
}
int main()
{
   CPerson me("Cooleaf");
   CPerson you("dummy");
   int i = 0;
   PF p[2];
   p[0] = CPerson::Slap;
   p[1] = CPerson::Kick;
   cin >> i;
   while (i != -1)
   {
      if (i > 1)
      {
         i = 1;
      }
      if (i < 0)
      {
         i = 0;
      }
      (me.*p[i])(you);
      cin >> i;
   }
   system("pause");
   return 0;
}
posted on 2006-01-06 17:48 cooelaf 阅读(594) 评论(1)  编辑 收藏 引用 所属分类: C++心得
Comments

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理