类成员函数指针 指向类中的非静态成员函数
#include <iostream> #include <functional> #include<algorithm> #include <vector> using namespace std; //函数指针指向一个类成员函数 class A { public: A(int aa = 0) :a(aa) {} ~A() {}; void SetA(int aa = 1) { a = aa; cout << "SetA" << endl; } private: int a; }; int main() { void (A::*ptr)(int) = &A::SetA; A a;
//对于指向类成员函数的函数指针,引用时必须传入一个类对象的this指针,所以必须由类实体调用 A* pa = &a; (pa->*ptr)(100); }
回调函数:函数指针作为参数传递
typedef void(*MPrint)(int a, int b); void Prints(int a,int b,const MPrint&func) { cout << a << b << endl; func(a, b); } void PrintSum(int a,int b) { cout << (a + b) << endl; } int main() { int a = 3; int b = 9; Prints(a,b, PrintSum); }
如何回调一个类成员函数?
函数指针无法指向类成员函数
使用std::bind 与std::function 结合的方式
class A { public: A(int aa = 0) :a(aa) {} ~A() {}; void SetA(int aa = 1) { a = aa; cout << "SetA" << endl; } void PrintSub(int c) { cout << (a - c) << endl; } private: int a; }; void Test(int c, std::function<void(int)>func) { cout << c << endl; func(c); } int main() { A a(9); std::function<void(int)>f1 = std::bind(&A::PrintSub, &a, std::placeholders::_1); Test(5,f1); }
标签:std,function,aa,函数,int,bind,函数指针,cout From: https://www.cnblogs.com/zsymdbk/p/16823577.html