局部类实现C++的闭包(二)

2013-04-10 11:53:07 · 作者: · 浏览: 568

 

  // 返回一个新的对象……这里必须得new,你懂的

  return new Test();

  }

  //////// 函数法实现 ////////////////////////////////////////

  // 定义测试函数指针类型

  typedef void (*Func)(const char*);

  // 下面函数返回一个闭包中的函数

  Func testFunc() {

  // 静态局部变量初始化为100

  static int count = 100;

  // 静态局部常量

  static const char* const NAME = "James";

  // 不能直接定义函数,只好定义局部类的静态方法,并返回其指针

  class Test {

  public:

  // 这个定义说明可以传入参数,同理也可以有返回值

  static void process(const char* pName = NULL) {

  if (pName == NULL) { pName = NAME; }

  cout << pName << " Count is " << count-- << endl;

  }

  };

  return Test::process;

  }

  //////// 程序入口:主函数 //////////////////////////////////

  int main(int argc, char* argv[]) {

  ITest* pT = test();

  Func pF = testFunc();

  // 多次调用得从函数里返回出来的函数和对象,观察结果

  for (int i = 0; i < 10; i++) {

  (*pT)();

  pF((i % 2 == 0) NULL : "Fancy");

  }

  }

  给个运行结果

  Count is 0

  James Count is 100

  Count is 1

  Fancy Count is 99

  Count is 2

  James Count is 98

  Count is 3

  Fancy Count is 97

  Count is 4

  James Count is 96

  Count is 5

  Fancy Count is 95

  Count is 6

  James Count is 94

  Count is 7

  Fancy Count is 93

  Count is 8

  James Count is 92

  Count is 9

  Fancy Count is 91

  C++(www.cppentry.com)是门非常灵活的语言,我们平时用到的相对于C++(www.cppentry.com) Specification来说,仅仅是冰山一角。虽然因为工作关系我已经有四五年没用它了,但它依然是我最喜欢的语言之一。