197_C++_一个较为新颖的C++中函数指针的应用【普通函数指针、类成员函数指针】

93 篇文章 3 订阅
这篇博客介绍了C++中如何使用函数指针和类成员函数指针作为回调函数。通过示例展示了如何在类的构造函数中传递普通函数和类成员函数的指针,并在特定事件触发时调用这些函数。同时,文中还展示了如何通过指针调用类的方法。
摘要由CSDN通过智能技术生成
#if 1

#include <iostream>
using namespace std;

//定义成全局,方便调用
class CEventQuery;

//注意函数指针的返回值类型、参数类型
typedef bool(*CommonFuncPoint)(void);                //普通函数指针
typedef bool (CEventQuery::*ClassFuncPoint)(int);   //类成员函数指针

bool CommonFunc(void)
{
	//这是个回调函数,当特定的事件或条件发生
	//的时候,会被调用。
	cout << "CallBackFunc Common Function Call!" << endl;
	//这里会有特定事件或条件发生时需要处理的事
	//....

	return true;
}

bool callback(void)
{
	cout << "回调函数!" << endl;
	return true;
}


class CEventQuery
{
public:
	CEventQuery(CommonFuncPoint eventFunc):m_Event(eventFunc)
	{
		//这里,参数传递到CommonFuncPoint eventFunc的eventFunc中
		//初始化列表的方式,把callback这个函数指针,赋值给m_Event
	}

	~CEventQuery() {}
	void Query(void)
	{
		//这里会检测某个事件或条件的发生        
		//比方说这里查询到了事件发生或条件的改变,那么就回调处理函数
		//执行m_Event,相当于执行callback
		m_Event();
	}
	bool DoSomething(int iValue)
	{
		cout << "Class Function DoSomething Parament : " << iValue << endl;
		return true;
	}
private:
	CommonFuncPoint m_Event;//相当于给CommonFuncPoint这个函数指针起别名
};

int main(void)
{
	//有参构造函数,传递函数名(函数名就是该函数的地址)
	//函数名相当于地址,只要该函数的返回值类型、参数类型和函数指针的返回值类型、参数类型一致,都可以作为参数使用
	CEventQuery tEventQuery(callback);
	tEventQuery.Query();

	//DoSomething的地址赋值给了ClassFunc1 ,ClassFuncPoint 类成员函数指针的别名
	ClassFuncPoint ClassFunc1 = &CEventQuery::DoSomething;
	//所以这里可以'.'出来ClassFunc1 
	(tEventQuery.*ClassFunc1)(10);
	tEventQuery.DoSomething(20);
	
	system("pause");
	return 0;
}

/*
===执行结果:===
回调函数!
Class Function DoSomething Parament : 10
Class Function DoSomething Parament : 20
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扳手的海角

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值