分享

C++之仿函数

 昵称14177824 2014-05-03

        最近突然想学一下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;
}
注意里面的引用方式


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多