C++ 如何将成员函数指针传递给另一个类
C++ How to pass member function pointer to another class?
这是我想要实现的:
class Delegate
{
public:
void SetFunction(void(*fun)());
private:
void(*mEventFunction)();
}
然后是名为 Test 的类
class Test
{
public:
Test();
void OnEventStarted();
}
现在在 Test() 中,我想像这样传递 OnEventStarted 来委托:
Test::Test()
{
Delegate* testClass = new Delegate();
testClass->SetFunction(this::OnEventStarted);
}
但是OnEventStarted是一个非静态的成员函数,我该怎么办?
为了调用成员函数,您需要指向成员函数和对象的指针。但是,鉴于成员函数类型实际上包括包含函数的类(在您的示例中,它将是void (Test:: *mEventFunction)();
并且仅适用于Test
成员,更好的解决方案是使用 std::function
。这是它的样子:
class Delegate {
public:
void SetFunction(std::function<void ()> fn) { mEventFunction = fn);
private:
std::function<void ()> fn;
}
Test::Test() {
Delegate testClass; // No need for dynamic allocation
testClass->SetFunction(std::bind(&Test::OnEventStarted, this));
}
你应该传递&Test::OnEventStarted
,这是成员函数指针的正确语法
之后,您必须获取 Test 类的实例才能像这样运行函数。
instanceOfTest->*mEventFunction()
相关文章:
- 修改函数中的指针(将另一个指针作为参数传递)
- 将指针分配给另一个指针时会发生什么情况?
- C++将一个指针分配给另一个指针时执行的类型检查
- 从另一个指针指向函数的指针
- 为什么通过定义另一个指针单元格,整个代码停止工作?
- C:试图将指针值复制到另一个指针中,得到可修改的左值错误
- 使用 SFINAE 测试是否可以将一个指针类型static_cast到另一个指针类型
- 将指针分配给另一个指针时会发生什么情况?
- 如何保存指针地址,以便另一个指针可以继续处理它
- 隐式指针变量,在自动定义中具有另一个指针变量
- RValue 引用在将其绑定(非指针)对象分配给另一个指针后是否会删除该对象?
- Valgrind:将一个指针分配给另一个指针后丢失字节
- 指针将其复制到另一个指针时的工作方式
- 从指针数组的元素传递地址以设置另一个指针地址
- 正在将指针指向的数据复制到另一个指针中
- C++:无法将指针的矢量分配给另一个指针的矢量
- 删除从另一个指针分配的指针,我应该再次删除另一个指针吗?
- 将一个指向成员函数的指针强制转换为同一类的另一个指针
- 访问指针数组/通过另一个指针并删除数组中的单个元素而不删除第一个指针或整个数组
- 在 C++ 中将一个指针复制到另一个指针