前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++ 中的函数对象(仿函数)的使用

C++ 中的函数对象(仿函数)的使用

作者头像
耕耘实录
发布2022-05-09 16:17:20
2K0
发布2022-05-09 16:17:20
举报
文章被收录于专栏:耕耘实录耕耘实录

函数对象,即一个重载了括号操作符“()”的对象。当用该对象调用此操作符时,其表现形式如同普通函数调用一般,因此取名叫函数对象。即重载函数调用操作符的类,其对象通常称为函数对象。函数对象使用重载()时,行为类似函数调用,因此也叫仿函数。

函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值。

代码语言:javascript
复制
#include<iostream>
using namespace std;

struct Add {
    int operator()(int v1, int v2) {
        return v1 + v2;
    }
};

void test() {
    Add add;
    cout<<add(10, 20)<<endl;
}

int main() {
    test();
    return 0;
}

函数对象超出普通函数的概念,可以有自己的状态。

代码语言:javascript
复制
#include<iostream>
#include <string>

using namespace std;

struct Print {
    Print() {
        this->count = 0;
    }

    void operator()(string demo) {
        cout << demo << endl;
        this->count++;
    }

    int count;
};

void test() {
    Print p;
    p("This is a demo.");
    p("This is a demo.");
    p("This is a demo.");
    p("This is a demo.");
    p("This is a demo.");
    cout << "Print打印输出的次数:" << p.count << endl; // 输出次数为5
}

int main() {
    test();
    return 0;
}

函数对象可以使用 new 创建对象:

代码语言:javascript
复制
#include<iostream>
#include <string>

using namespace std;

struct Print {
    Print() {
        this->count = 0;
    }

    void operator()(string demo) {
        cout << demo << endl;
        this->count++;
    }

    int count;
};

void test() {
    auto *p = new Print();
    (*p)("This is a demo.");
    (*p)("This is a demo.");
    (*p)("This is a demo.");
    (*p)("This is a demo.");
    cout << "Print打印输出的次数:" << p->count << endl;
    delete p;
    p = nullptr;
}

int main() {
    test();
    return 0;
}

函数对象可以作为参数进行传递。

代码语言:javascript
复制
#include<iostream>
#include <string>

using namespace std;

struct Print {
    Print() {
        this->count = 0;
    }

    void operator()(string demo) {
        cout << demo << endl;
        this->count++;
    }

    int count;
};

void do_print(Print &p, string s){
    p(s);
}

void test() {
    auto *p = new Print();
    do_print((*p),"This is a demo.");
    delete p;
    p = nullptr;
}

int main() {
    test();
    return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-02-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档