栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

函数对象(可调用对象2)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

函数对象(可调用对象2)

一、定义

   定义:重载了()操作符的类/结构体

#include 
#include 
#include 
using namespace std;

//定义了一个函数对象(仿函数)
struct MyTest
{    
    void operator()(string msg)  // 重载了()运算符
    {
        cout << msg << endl;
    }
};

int main(void)
{
    MyTest t;
    t("mata"); //像函数一样调用
    return 0;
}

二、使用
#include 
#include 
#include 
using namespace std;

// 函数对象
template
struct LessThan
{

    LessThan(const T& threshold){
        this->_threshold = threshold;
    }

    bool operator()(const T& value1) // 重载了()operator
    {
        return value1 < _threshold;  //非基础类型 要重载 < operator
    }

    T _threshold;
};

int countIf(int* begin, int* end, std::function func)
{
    int count = 0;
    for (int* pt = begin; pt != end; pt++)
    {
        count = func(*pt) ? count + 1 : count; //调用了bool operator()(const T& value1)
    }
      
    return count;
}



int main()
{
    
    int arr[5] = { 1, 2, 13, 14,15 };

    // 统计小于10的个数
    LessThana(10);
    // 传递一个可调用对象(这里是一个函数对象)
    int count = countIf(arr, arr + 5, a);

    // 传递一个匿名的可调用对象(这里是一个函数对象)
    int count1 = std::count_if(arr, arr + 5, LessThan(10));
    std::cout << count << std::endl;
    std::cout << count1 << std::endl;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/290599.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号