zoukankan      html  css  js  c++  java
  • 函数对象和函数指针

    1. 定义:
        函数对象:所有重载了函数调用操作符(operator())的类对象,又称为函数子。在STL中,大多数使用函数子的地方都可以使用函数指针(ps:set和multiset的比较类型必须是函数对象,而不能是函数指针)通过将operator设置为内联函数,可以使程序性能加速。
        函数指针:指向某种(函数参数,返回值)的函数类型的指针,每个函数都有一个入口地址,函数指针便是指向了函数的入口地址。通过将函数指针传入函数中,方便一个函数调用另一类型的函数。如: int GetMaxValue( double x, bool (*ptr)(int, int) ),其中ptr即为函数指针。 
         c++中这样使用函数指针:
    bool greaterNum(int x, int y)
    {
        return x>y;
    }                 
    using PF = bool (*)(int, int);  //或typedef int (*PF)(int, int);
    PF pf = greaterNum;
    cout<<pf(4,10)<<endl; //输出为0
    2. 例子:
        使用函数指针和函数对象作为STL中sort的参数,实#include <iostream>
    #include <vector>
    #include <algorithm>
    #include <functional>
    
    using namespace std;
    
    template<typename T>
    class GreaterNum : public binary_function<T, T, bool>
    {
    public:
        inline bool operator()(T x, T y)
        {
            return x>y;
        }
    };
    
    bool greaterNum(int x, int y)
    {
        return x>y;
    }
    
    void print(int x)
    {
        cout<<x<<" ";
    }
    
    int main()
    {
        vector<int> v1 = {21,6,21,4,2,1,45,6,1,7,9,5,2};
        auto v2 = v1;
        /*使用函数对象为第三个参数*/
        sort( v1.begin(), v1.end(), GreaterNum<int>() );
        for_each(v1.begin(), v1.end(), print);
        cout<<endl;
        /*使用函数指针为第三个参数*/
        sort( v2.begin(), v2.end(), greaterNum );
        for_each(v2.begin(), v2.end(), print);
        
        return 0;
    }
    3. 函数对象的优势:
        (1)函数对象通过重载()实现,那么将operator()函数设置为内联函数,可以提高程序的运行速度。如上面的例子,相比于传入greaterNum函数指针为sort的第三个形参,传入是GreaterNum<int>函数子时,程序运行的速度快。因为内联函数在编译时展开,而函数指针要进行调用。
        (2)函数对象可以携带附加信息,如类的其他数据成员,而函数指针则做不到。
  • 相关阅读:
    VS 2010下一次性配置opencv(32位和64位相同)
    模拟鼠标事件
    Main函数参数argc,argv说明
    Visual Studio 2010 LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏解决方案
    常量指针和指针常量
    strlen函数实现的几种方法
    杀死指定的进程名
    typedef和typename关键字
    如何理解dart的mixin
    c# 通过dllimport 调用c 动态链接库
  • 原文地址:https://www.cnblogs.com/ladawn/p/8318819.html
Copyright © 2011-2022 走看看