谈函数指针(全局_类成员函数)和函数对象

文章作者 100test 发表时间 2007:10:24 14:07:43
来源 100Test.Com百考试题网


  函数指针(全局函数/类成员函数)、函数对象(Function object)

  一. 函数指针类型为全局函数.

以下是引用片段:
  #include "stdafx.h"
  #include
  using namespace std.
  class TestAction.
  typedef void (*fp)(int).
  void Drink(int i)
  {
  cout<<"No. "<
  }
  void Eat(int i)
  {
  cout<<"No. "<
  }
  class TestAction
  {
  public:
  fp testAct.
  void TestAct(int i)
  {
  if (testAct != NULL)
  {
  testAct(i).
  }
  }
  }.
  int main(int argc, char* argv[])
  {
  TestAction doact.
  doact.testAct = &.Drink.
  doact.TestAct(0).
  doact.TestAct(1).
  doact.TestAct(2).
  doact.testAct = &.Eat.
  doact.TestAct(0).
  doact.TestAct(1).
  doact.TestAct(2).
  return 0.
  }

  二. 函数指针类型为类成员函数.

以下是引用片段:
  #include "stdafx.h"
  #include
  using namespace std.
  class Action.
  class TestAction.
  // 函数指针类型为类 Action 的成员函数
  typedef void (Action::*fp)(int).
  class Action
  {
  public:
  void Drink(int i)
  {
  cout<<"No. "<
  }
  void Eat(int i)
  {
  // 本文转自 C Builder 研究 - http://www.ccrun.com/article.asp?i=1005&.d=sc37og
  cout<<"No. "<
  }
  }.
  class TestAction
  {
  public:
  // 定义一个函数指针
  fp testAct.
  //Action 对象实例 , 该指针用于记录被实例化的 Action 对象
  Action * pAction.
  void TestAct(int i)
  {
  if ((pAction != NULL) &.&. (testAct != NULL))
  {
  // 调用
  (pAction->*testAct)(i).
  }
  }
  }.
  int main(int argc, char* argv[])
  {
  Action act.
  TestAction doact.
  doact.pAction = &.act.
  doact.testAct = Action::Drink.
  doact.TestAct(0).
  doact.TestAct(1).
  doact.TestAct(2).
  doact.testAct = Action::Eat.
  doact.TestAct(0).
  doact.TestAct(1).
  doact.TestAct(2).
  return 0.
  }


相关文章


windows强化安全综合设置
在C 程序中添加逻辑流程控制
转:从VC 到GCC移植:谈两者语法差异
C_C 中动态链接库的创建和调用
谈函数指针(全局_类成员函数)和函数对象
A .NET效率陷阱之——Attributes
并非偏见也驳“驳’C语言已经死了’”
神话与谬误:争论C 前你应当知道什么
使用Rational进行C 转换的技巧
澳大利亚华人论坛
考好网
日本华人论坛
华人移民留学论坛
英国华人论坛