C++中几种常见的可调用对象

 1. 函数指针(Function Pointer):

void foo(int x) {
    // do something
}

// 定义函数指针类型
typedef void (*FuncPtr)(int);

// 创建函数指针对象并进行调用
FuncPtr ptr = foo;
ptr(10);
 

2. 函数对象(Function Object):

struct Functor {
    void operator()(int x) {
        // do something
    }
};

Functor functor;
functor(10);
 

3. Lambda 表达式:

auto lambda = [](int x) {
    // do something
};

lambda(10);
 

4. std::function:

#include <functional>

void foo(int x) {
    // do something
}

std::function<void(int)> func = foo;
func(10);
 

5. 成员函数指针(Member Function Pointer):

class MyClass {
public:
    void memberFunc(int x) {
        // do something
    }
};

typedef void (MyClass::*MemFuncPtr)(int);

MyClass obj;
MemFuncPtr memFuncPtr = &MyClass::memberFunc;
(obj.*memFuncPtr)(10);
 

6. std::bind:

#include <functional>

void func(int a, int b, int c) {
    // do something
}

auto boundFunc = std::bind(func, 10, std::placeholders::_1, 20);
boundFunc(30); // 等价于 func(10, 30, 20)
 

定义函数指针:

  1. 使用typedef关键字:

typedef void (*FuncPtr)(int); 

    2.使用类型别名(Type Alias):

using FuncPtr = void (*)(int);

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值