1.C++函数指针
指向普通函数:
语法:函数类型+(指针)(参数类型)= 所指函数
bool (*p)(int) = func;
bool (&p)(int) = func;
p(10);
指向类成员函数:
#include "iostream"
using namespace std;
class Func
{
public:
void operator()()
{
cout << "operater()" << endl;
}
};
class Base
{
public:
int a;
int b;
void display()
{
cout << "Base Display" << endl;
}
static void count()
{
cout << "Base Count" << endl;
}
};
int main()
{
void (Base::*p)() = &Base::display;
Base base;
(base.*p)();//调用完无需绑定对象
void (*p1)() = &Base::count;
p1();//调用时无需绑定对象
}
2.std:function
分为五种情况:
封装普通函数;
封装仿函数;
封装类函数;
封装静态类函数;
封装lambda表达式
#include "iostream"
#include "functional"
using namespace std;
class Base
{
public:
int a;
int b;
void display()
{
cout << "Base Display" << endl;
}
static void count()
{
cout << "Base Count" << endl;
}
};
class Func2
{
public:
void operator()()
{
cout << "operater()" << endl;
}
};
void Func1(const string str)
{
cout << str + str << endl;
}
int main()
{
//封装普通函数
function<void(const string)>funcA = Func1;
funcA("aabb");
//封装仿函数
function<void()>funcB = Func2();
funcB();
//封装类函数
Base base;//创建一个Base类的对象
function<void()>funcC = bind(&Base::display,&base);
funcC();
//封装静态类函数
function<void()>funcD = Base::count;
funcD();
//封装lambda表达式
string str;
auto f = [&](int val){
str = "值:";
cout << str << " " << val << endl;
};
function<void(int)>funcE = f;
funcE(30);
}
3.std:bind
std:bind——将函数或可调用对象与特定参数绑定,从而创建一个新的可调用对象;
#include "iostream"
#include "functional"
using namespace std;
void hello(string str)
{
cout << "hello " << str << endl;
}
class Chello
{
public:
void h(string str)
{
cout << "hello " << str << endl;
}
};
class likehello
{
public:
void operator()(string str)
{
cout << "hello " << str << endl;
}
};
int main()
{
//bind绑定普通函数和参数
auto fhello = bind(&hello,"Tim");
fhello();//调用被绑定的hello函数就不用传入参数
//bind绑定类函数和参数
Chello c1;
auto chello = bind(&Chello::h,&c1,"cook");
chello();
//bind绑定仿函数
auto lhello = bind(likehello(),"TimCook");
lhello();
}