c++ 函数指针的使用和回调

最近写代码用到函数指针,在此总结下,以便后面使用

一、普通函数指针的使用

typedef double (*CallBackPtr)(int x,double y);            // 定义一个函数指针类型

double myFunc1(int x,double y)
{
    cout << "普通函数指针   myFunc1 " << x << endl;
	return 2;
}

double callMyFunc(CallBackPtr cb, int x,double y)
{
    return (*cb)(x,y);
}

int main()
{
	callMyFunc(myFunc1,1000000000,6 );    //普通函数指针的使用

	Test t;
	t.Tests();

    return 0;
}

在这上面的代码中,首先编写调用函数 “myFunc1”,这样就确定了用传的参数个数和类型, 用typedef 申明调用函数实参别名,也可以不用,就是写起来麻烦。使用callMyFunc 作为中间过渡,我们可以在这里写相同操作的代码。

有两个地方需要注意:1. typedef 时候是 (*CallBackPtr),需要带“*”和“()”, 2.  callMyFunc 中 “(*cb)(x,y)” 可以改成“cb(x,y)”,结果都一样(我没想明白,以后再研究); 

二、同一个类下

在上面的代码中,我调用一个类Test,在这里怎么调用一个类中的函数

Test.cpp 文件

double Test::myFunc2(int x,double y)
{
    cout << "Test 类中的  myFunc2  " << x << endl;
	return 2;
}

double Test::callMyFunc(CallBackPtr cb, int x,double y)
{
    return (this->*cb)(x,y);
}

void Test::Tests()
{

	callMyFunc((CallBackPtr)(&Test::myFunc2), 11111,3);   //调用同-个类

	callMyFunc((CallBackPtr)(&test1::myFunc3),22222,6 );

	callMyFunc((CallBackPtr)(&test2::myFunc4),333333,6 );

	test1 t1;
	t1.MyTest1(44444444,55555555);
}
Test.h
#pragma once
using namespace std;

class Test;  //声明这个类,为后面使用做准备, 必须加

class Test
{
typedef double (Test::*CallBackPtr)(int x,double y);            // 定义一个函数指针类型

public:
	Test(void);
	~Test(void);

	void Test::Tests();

	double Test::callMyFunc(CallBackPtr cb, int x,double y);
	double Test::myFunc2(int x,double y);
};

在.h文件中, 需要添加  "class Test; "   这个必须加不然程序报错, typedef 重命名时与普通函数指针调用有区别,(Test::*CallBackPtr)在前面要加上类名"Test::",

在cpp文件中,调用过渡函数“callMyFunc”时,传递函数名时“(CallBackPtr)(&Test::myFunc2)”需要 :1. 强制转换, 2. 函数名前" &Test:: " 取地址和加类名 。 在 函数“callMyFunc”中,使用函数指针时,要加“this”和“*”(即:(this->*cb))。

3. 调用其他类中的函数

在上面“Test。cpp” 中,我还调用了 “test2”这个类,里面只有这一个函数。

double test2::myFunc4(int x,double y)
{
    cout << "test2 类中的  myFunc4 " << x << endl;
    return 2;
}

调用其他类函数需要注意:传递函数的写法“(CallBackPtr)(&test2::myFunc4)”,还是需要强制转换和取地址添加类名,过渡函数和同一个类调用一样,注意 “(this->*cb)”这里。

下面是运行结果:

c++ 函数指针的使用和回调_第1张图片


这是我写的测试源码:

https://download.csdn.net/download/chen1231985111/10314933


你可能感兴趣的:(c,函数指针,函数指针同一个类的使用)