CPP 核心编程4-重载函数调用运算符

本文介绍C++中函数调用运算符重载的概念,通过创建仿函数类实现类似于函数调用的操作,并展示了如何使用这些类进行数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

#include "iostream"

using namespace std;

//函数调用运算符重载
//打印输出类
class MyPrint {
public:
    //重载函数调用运算符
    void operator()(string str) {
        cout << "仿函数:" << str << endl;
    }
};

void MyPrint(string str) {
    cout << "全局函数MyPrint:" << str << endl;
}

void mp(string str) {
    cout << "全局函数mp:" << str << endl;
}

class MyAdd {
public:
    int operator()(int a, int b) {
        return a + b;
    }
};

void test1() {
    class MyPrint mp;//这里由于类和全局函数一致,所以这里需要加class
    MyPrint("hello world");//由于使用起来非常类似函数调用,因此称为仿函数
    mp("hello world");//由于使用起来非常类似函数调用,因此称为仿函数
}

void test2() {
    MyAdd myAdd;
    int sum = myAdd(1, 2);
    cout << "sum=" << sum << endl;
    cout << endl;
    //匿名函数对象
    int sum2 = MyAdd()(1, 2);
    cout << "sum2=" << sum2 << endl;
    cout << endl;
}

int main() {
    test1();
    cout << endl;
    test2();
    return 0;
}
全局函数MyPrint:hello world
仿函数:hello world

sum=3

sum2=3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值