c++回调包含类函数回调和非类函数回调。
类函数回调,函数指针指向函数名称,需要带类作用域,调用时需要用到类指针。
如qt里面定义一个返回值为qbytearray的函数指针,
typedef QByteArray (myThead::*Func_Construct)(QByteArray line);//定义函数指针 QByteArray deviceStatus_construct(QByteArray); QByteArray realData_construct(QByteArray line); QByteArray dayRun_construct(QByteArray); QByteArray monthCheck_construct(QByteArray line); QByteArray flag_construct(QByteArray line); QByteArray palarm_construct(QByteArray line); QByteArray deviceDefine_construct(QByteArray line); QByteArray staff_construct(QByteArray line); QByteArray deviceStatus_construct_str(QString line); case e_deviceStatus: pFunc = &myThead::deviceStatus_construct; break; case e_realData: pFunc = &myThead::realData_construct; break; case e_dayRun: pFunc = &myThead::dayRun_construct; break; case e_monthCheck: pFunc = &myThead::monthCheck_construct; break; case e_flag: pFunc = &myThead::flag_construct; break; case e_palarm: pFunc = &myThead::palarm_construct; break; case e_deviceDefine: pFunc = &myThead::deviceDefine_construct; break; case e_staff: pFunc = &myThead::staff_construct; 回调: QByteArray btLine = (this->*pFunc)(strLine.toUtf8());
非类指针则简单得多:
1 typedef void (*Func)(int ,int ) 2 void func1(int numA,int numB){ 3 printf(numA+numB); 4 } 5 6 void func2(int numA,int numB){ 7 printf(numA - numB); 8 } 9 10 int main(){ 11 int numA = 10; 12 int numB=5; 13 Func pFunc = &func1; 14 pFunc (numA ,numB); 15 pFunc = &func2; 16 pFunc(numA,numB); 17 return0; 18 }