嘿,我想在 C++ 中实现委托(delegate),我知道如何在 C# 中执行,我发布了我的代码,但不知道如何将其转换为 C++
public class Events {
public delegate void Action();
public Action OnPrintTheText = delegate{};
}
public class ABC {
private Event evt;
public ABC() {
evt = new Event();
}
public void printText() {
evt.OnPrintTheText();
}
public Event getEventHandler() {
return evt;
}
}
public class Drived {
private ABC abc;
public Drived() {
abc = new ABC();
abc.getEventHandle().OnPrintTheText += OnPrint;
}
~Drived() {
abc.getEventHandle().OnPrintTheText -= OnPrint;
}
public void OnPrint() {
Debug.Log("ABC");
}
}
现在,每当我调用 printText 时,它都会自动调用 Drived 类的 OnPrint(),那么是否可以将其实现为 c++?
最佳答案
C# 在幕后做了很多管理工作。从广义上讲,C# 中的委托(delegate)是函数引用的容器。
在 C++ 中,您可以使用仿函数模板创建类似的委托(delegate),仿函数模板包装对象实例和类成员函数的成员函数,也可以只包装函数(对于非成员)。然后您可以使用标准容器来维护仿函数实例的列表/数组/映射/等,这将为您提供 C# 委托(delegate)的功能,还允许添加和删除“操作”(C#:+=和-=)。
请看我的回答here关于如何为类成员创建这样的模板仿函数。非成员情况更简单,因为它不包装对象实例。
关于c# - C++中的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22132023/