最近突然想学一下C++之仿函数。得到的心得记录一下,以备日后继续学习及复习今日之所得是否正确。至于仿函数的概念在这里不作解释,只要明白仿函数是一个类,我们可以用这个类的对象当函数使用。 先上代码。 #include <stdio.h> #include <iostream> using namespace std; template<typename T> class CTemplateTest { public: CTemplateTest<T>(T *expObj) : obj(expObj) { }; /*CTemplateTest<T>(T &expObj) : obj(expObj) { }; */ ~CTemplateTest<T>() { }; public: T *obj; //T obj; 非指针时 virtual void setDate(int a) { obj->operator()(a); //obj.operator()(a);or obj(a); 非指针时调用方法 } bool isTrue() { return true; } }; class CMy { public: CMy(int vale); ~CMy(); int val; public: void operator()(int a) { run(a); } void printfMy(); private: void run(int a); }; #include "stdafx.h" #include "TemplateTest.h" CMy::CMy(int vale) :val(vale) { val = vale; } CMy::~CMy() { } void CMy::printfMy() { cout <<"this is test:"<< this->val << endl; } void CMy::run(int a) { val = a; } // learnTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <iostream> #include "TemplateTest.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { CMy *obj = new CMy(100); CTemplateTest<CMy> *nobj = new CTemplateTest<CMy>((obj)); //CTemplateTest<CMy> *nobj = new CTemplateTest<CMy>(*(obj)); nobj->setDate(50); obj->printfMy(); return 0; } 注意里面的引用方式 |
|
来自: 昵称14177824 > 《C 》