大家好:我是一位经验丰富的 c# 程序员,试图在 c++ 中做一些工作,但我不确定这样做的正确方法:
我正在创作一个需要通知消费类发生了什么事的类。
如果我用 c# 编写这个,我会在我的类上定义一个事件。
c++ 中没有事件,所以我试图找出正确的方法是什么。我已经考虑过回调函数,但是如何处理我想要执行成员函数(不是静态函数)的情况。
更具体地说,我真正需要做的是处理事件,但可以访问处理事件的对象实例中的成员状态。
我一直在研究 std::tr1:function,但我无法让它工作。
我不认为有人想将以下示例 c# 示例转换为正确/最佳实践 c++ 的示例(我需要 ANSI c++)?(请记住,我几乎没有 c++ 经验——不要假设我知道任何长期建立的 c++ 约定——我不知道;);
一个简单的 c# 控制台应用程序(在我的机器上工作):
using System;
namespace ConsoleApplication1
{
public class EventSource
{
public event EventHandler<EchoEventArgs> EchoEvent;
public void RaiseEvent(int echoId)
{
var echoEvent = this.EchoEvent;
if (echoEvent != null)
echoEvent(this, new EchoEventArgs() {EchoId = echoId});
}
}
public class EchoEventArgs : EventArgs
{
public int EchoId { get; set; }
}
public class EventConsumer
{
public int Id { get; set; }
public EventConsumer(EventSource source)
{
source.EchoEvent += OnEcho;
}
private void OnEcho(object sender, EchoEventArgs args)
{
// handle the echo, and use this.Id to prove that the correct instance data is present.
Console.WriteLine("Echo! My Id: {0} Echo Id: {1}", this.Id, args.EchoId);
}
}
internal class Program
{
private static void Main(string[] args)
{
var source = new EventSource();
var consumer1 = new EventConsumer(source) { Id = 1 };
var consumer2 = new EventConsumer(source) { Id = 2 };
source.RaiseEvent(1);
Console.ReadLine();
}
}
}