当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
计算机二级辅导:CPPTemplates之仿函数
发布时间:2009/11/25 16:11:16 来源:城市学习网 编辑:admin

  // bolgcontent.cpp : 定义控制台应用程序的入口点。
  //
  #include "stdafx.h"
  #include <iostream>
  #include <string>
  //仿函数
  //一、函数指针和函数引用
  //例如:
  #include <typeinfo>
  void foo()
  {
  std::cout<<"foo() called"<<'\n';
  }
  typedef void FooT();//FooT 是一个函数类型
  int _tmain(int argc, _TCHAR* argv[])
  {
  foo();//直接调用
  std::cout<<"Types of foo:"<<typeid(foo).name()<<'\n';
  std::cout<<"Types of foo:"<<typeid(FooT).name()<<'\n';
  FooT *pf=foo;//隐式转型
  pf();//通过指针的间接调用
  (*pf)();//等价于pf()
  //输出pf的类型
  std::cout<<"Types of foo:"<<typeid(pf).name()<<'\n';
  FooT & rf=foo;//没有隐士转换
  rf();//通过引用的间接调用
  //输出rf的类型
  std::cout<<"Types of foo:"<<typeid(rf).name()<<'\n';
  return 0;
  }
  // bolgcontent.cpp : 定义控制台应用程序的入口点。
  //

  #include "stdafx.h"
  #include <iostream>
  #include <string>
  //仿函数
  //二、class类型的仿函数
  //在cpp中,虽然函数指针就是现成的仿函数;然而在很多情况下,如果使用重载了函数调用
  //运算符的class类型对象的话,可以给我们带来很多的好处:譬如灵活性、性能甚至两者兼
  //备
  //例如:
  class ConstantIntFunctor
  {
  private:
  int value;//仿函数调用 所返回的值
  public:
  ConstantIntFunctor(int c):value(c)
  {}
  //函数调用
  int operator() ()
  {
  return value;
  }
  };
  //使用上面函数对象的客户端函数
  void client(ConstantIntFunctor & cif)
  {
  std::cout<<"call back functor yields "<<cif()<<'\n';
  }
  int _tmain(int argc, _TCHAR* argv[])
  {
  ConstantIntFunctor seven(7);
  ConstantIntFunctor fortytwo(42);
  client(seven);
  client(fortytwo);
  return 0;
  }

广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved