C++中的仿函数使用

1、仿函数的概念

仿函数是一个是通过重载()运算符模拟函数形为的类。

2、实现方法

下面是一个简单的实现方法:

//看看字符串是否小于一个长度
class Test{
    public:
        explicit Test(int lenth) : len(lenth){}

        bool operator() (const QString& str) const{
             return str.length() < len;
        }

    private:
        const int len;
};


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

    QString str = "abcde";
    int len1 = str.length()-1;
    int len2 = str.length()+1;

    //使用方法1
    qDebug()<<Test(len1)(str)<<endl;
    //使用方法2
    Test t(len2);
    qDebug()<<t(str)<<endl;

    return a.exec();
}

 3、仿函数的应用场景

对于上面应用,很明显,可以简单定义一个比较的函数,用来处理字符长度的比较工作。因此,如果想要利用仿函数,一定是需要用到仿函数类的功能,譬如:仿函数类定义的时候,可以传递一个参数,()操作的时候,也可以传递参数,两种参数有作用优先级的时候,可以考虑这种使用方法。下面实现一个简单工厂模式:

class Operation
{
public:
    int a = 0;
    int b = 0;
    Operation(int ia,int ib){
        a = ia;
        b = ib;
    }
public:
    virtual bool GetResult(int) =0;

};

class OperateIn:public Operation
{
public:
    OperateIn(int ia,int ib): Operation(ia, ib) {}
    //判断输入的i是否在 a和b 之间
    bool GetResult(int i)
    {
        if(i>a && i<b)
            return true;
        return false;
    }
};

class OperateOut:public Operation
{
public:
    OperateOut(int ia,int ib): Operation(ia, ib) {}
    //判断输入的i是否在 a和b 之外
    bool GetResult(int i)
    {
        if(i>a && i<b)
            return false;
        return true;
    }
};

//工厂类
class Test{
    public:
        Operation *opt = nullptr;
        explicit Test(char op) : operate(op){}
        //通过仿函数,返回实际的对象
        Operation* operator() (int a,int b){

            switch(operate)
            {
                case 'i':
                    opt = new OperateIn(a,b);
                    break;
                case 'o':
                    opt = new OperateOut(a,b);
                    break;

            }
            return opt;

        }

    private:
        const char operate;

};


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


    Test t('i');
    Operation *pt = t(1,5);
    qDebug()<<pt->GetResult(3)<<endl;
    qDebug()<<pt->GetResult(7)<<endl;
    pt = t(1,8);
    qDebug()<<pt->GetResult(3)<<endl;
    qDebug()<<pt->GetResult(7)<<endl;


    Test t2('o');
    pt = t2(1,5);
    qDebug()<<pt->GetResult(3)<<endl;
    qDebug()<<pt->GetResult(7)<<endl;

    return a.exec();
}

可以看到,通过类定义,传递“i”和“o”两种操作方法,()将作用范围传递进去

原文地址:https://www.cnblogs.com/pinking/p/12230460.html