一 可调用对象
本节课将可调用对象整理一下
1 函数指针
void func90(int tv) {
cout << "func90(int tv) called tv = " << tv << endl;
}
void main() {
//可调用对象 1 函数指针
//方式一 1.1定义一个函数指针对象pmf
void(*pmf)(int);
//1.2将函数名赋值给函数指针
pmf = func90;
//1.3通过函数指针调用该函数
pmf(2);
//方式二 1.1 定义一个函数指针对象pmf1,并直接将函数名赋值给pmf1函数指针
void(*pmf1)(int) = func90;
//1.2通过函数指针调用该函数
pmf1(20);
}
2.具有operator()成员函数的类对象(仿函数)
仿函数 functor,通过在类中重载()运算符 实现
//2.具有operator()成员函数的类对象仿函数()
class Teacher90 {
public:
int operator()(double a ,string s) {
cout << "operator()(double a ,string s) called a = " << a <<" s = "<<s << endl;
return 111;
}
int operator()() {
cout << "operator()called " << endl;
return 222;
}
};
void main() {
//2.1通过匿名对象调用
Teacher90()();
Teacher90()(89,"nihao");
//2.2
Teacher90 tea;
tea();
tea(90,"haode");
//2.3
tea.operator()();//等价于 tea();
tea.operator()(80,"sdf"); //等价于 tea.(80,"sdf");
}
3. 可被转换为函数指针的类对象
//3. 可被转换为函数指针的类对象
class Teacher91 {
public:
using tfpoint = void(*)(int);//1.定义一个函数指针类型,
operator tfpoint() {//2.将operator 和 函数指针 结合使用,这里的含义是 opearator的返回值类型为Teacher91::tfpoint
return mysfunc; //3. 需要return一个 返回值类型为Teacher91::tfpoint 的函数指针类型,因此要找一个函数返回,该函数的返回值是void,参数是int的
//return NULL; 如果return NULL 会有run time exception
}
static void mysfunc(int tv) {
cout << "Teacher91::mysfunc() 静态成员函数执行了 tv = " << tv << endl;
}
};
void main() {
Teacher91 tea;
tea(90);//先调用tfpoint()函数,再调用mysfunc函数,等价于tea.operator Teacher91::mysfunc()(90);
}
4. 类成员函数指针
注意写法有点不同
//4. 类成员函数指针
class Teacher92 {
public:
void func(int vt) {
cout << "void func(int vt) call vt = " << vt << endl;
}
};
void main() {
//方式1
void (Teacher92::*pointfunc)(int) = &Teacher92::func;
Teacher92 tea;
(tea.*pointfunc)(89);
//方式2
void (Teacher92::*pointfunc1)(int);
pointfunc1 = &Teacher92::func;
Teacher92 tea1;
(tea1.*pointfunc1)(99989);
}
5.总结
二 std::function(可调用对象包装器)
如何把上述4种不同的可调用对象的形式统一一下,统一的目的是方便咱们调用。
就要用到 <

本文详细介绍了C++中的可调用对象(如函数指针、仿函数和类对象),以及std::function和std::bind这两个工具如何统一处理和绑定这些对象,包括它们的用法、特点和适用场景。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



