How can I pass a class member function as a callback?(如何将类成员函数作为回调传递?)
问题描述
我使用的 API 要求我将函数指针作为回调传递.我正在尝试从我的班级中使用此 API,但出现编译错误.
I'm using an API that requires me to pass a function pointer as a callback. I'm trying to use this API from my class but I'm getting compilation errors.
这是我在构造函数中所做的:
Here is what I did from my constructor:
m_cRedundencyManager->Init(this->RedundencyManagerCallBack);
这无法编译 - 我收到以下错误:
This doesn't compile - I get the following error:
错误 8 错误 C3867:'CLoggersInfra::RedundencyManagerCallBack':函数调用缺少参数列表;使用&CLoggersInfra::RedundencyManagerCallBack"创建一个指向成员的指针
Error 8 error C3867: 'CLoggersInfra::RedundencyManagerCallBack': function call missing argument list; use '&CLoggersInfra::RedundencyManagerCallBack' to create a pointer to member
我尝试了使用 &CLoggersInfra::RedundencyManagerCallBack
的建议 - 对我不起作用.
I tried the suggestion to use &CLoggersInfra::RedundencyManagerCallBack
- didn't work for me.
对此有何建议/解释??
Any suggestions/explanation for this??
我使用的是 VS2008.
I'm using VS2008.
谢谢!!
推荐答案
这不起作用,因为成员函数指针不能像普通函数指针一样处理,因为它需要一个this"对象参数.
That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument.
相反,您可以传递一个静态成员函数,如下所示,在这方面就像普通的非成员函数:
Instead you can pass a static member function as follows, which are like normal non-member functions in this regard:
m_cRedundencyManager->Init(&CLoggersInfra::Callback, this);
函数可以定义如下
static void Callback(int other_arg, void * this_pointer) {
CLoggersInfra * self = static_cast<CLoggersInfra*>(this_pointer);
self->RedundencyManagerCallBack(other_arg);
}
这篇关于如何将类成员函数作为回调传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将类成员函数作为回调传递?


基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01