类C#中的C#事件,组合 [英] C#-like events in C++, Composition

查看:121
本文介绍了类C#中的C#事件,组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几个月里,我一直在使用C#,并习惯了事件和代表。它是非常容易使用组合在你的类,只是使用事件从组件中获取消息...现在我想做一些类似的C ++,不知道该怎么做。

For the last couple of months I've been using C# a lot and got used to events and delegates. Its is very easy to use composition in your classes, just use events to get messages from the component... Now I'm trying to do something similar in C++ and don't know how to do it.

如何在C ++中完成组合?我想到的唯一途径是继承...你从类中派生并重写其函数以接收来自它的输入?是否有其他更简单(更好)的方式?

How is composition done in C++? The only way that comes to my mind is inheritance... you derive from the class and override its functions to receive input from it? Is there any other easier (better) way?

要进一步解释...

一个可重用的组件像这样...

I want to write a reusable component like this...

public delegate void OnDataReceivedHanlder(byte[] data);
public class TcpConnection
{
    public void Connect(string iP, ushort port);
    public void Send(byte[] data);
    public event OnDataReceivedHandler OnDataReceived;    
}

在C ++ ...

推荐答案

通常,您将使用继承(动态或静态)。或者,您只需使用 std :: function< return(args ..)> ,它可以绑定到多个选项,如函数对象,函数指针,lambda函数等。

Typically, you will use inheritance (either dynamic or static) for this. Alternatively, you would just use a std::function< return(args..) >, which can be bound to a number of alternatives, like function objects, function pointers, lambda functions, etc.

这篇关于类C#中的C#事件,组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆