1

我对 C++ 中的虚函数有疑问。我花了最后一个小时搜索,但我没有快速找到任何地方,我希望你能提供帮助。
我有一个处理传输和接收数据的类。我希望该类尽可能模块化,因此我想创建一个抽象/虚拟方法来处理接收到的消息。
虽然我知道我可以创建一个新类并覆盖虚拟方法,但我真的不想创建大量新类,它们都以不同的方式实现该方法。在 Java 中,您可以在声明对象时使用侦听器和/或覆盖代码主体中的抽象方法,如示例中所示。

JTextField comp = new JTextField();   
comp.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        //Handler Code
    }
});

这在 C++ 中是可能的还是有更好的方法来解决这类问题?

干杯,非常感谢,
克里斯。

4

3 回答 3

3

看看这个其他 SO 帖子是否 C++0x 支持匿名内部类,因为问题听起来很相似。

函子(函数对象)或 lambda 可能是合适的替代方案。

于 2013-08-19T12:01:44.893 回答
1

在 C++ 中,您需要声明一个新类:

class MyActionListener: public ActionListener
{
    public:
       void actionPerformed(ActionEvent evt) { ... code goes here ... }
}; 
于 2013-08-19T11:54:37.447 回答
0

这个问题已经得到了回答,但我想我会很好地解决这个问题。示例中链接的 SO 讨论很好,但主要集中在复制 Java 体验上。这是一种更惯用的 C++ 方法:

struct EventArgs
{
    int param1;
    int param2;
};

class network_io
{
    typedef std::function<void (EventArgs)> Event;
    typedef std::vector<Event> EventList;

    EventList Events;

public:
    void AddEventHandler(Event evt)
    {
        Events.push_back(evt);
    }

    void Process()
    {
        int i,j;
        i = j = 1;
        std::for_each(std::begin(Events), std::end(Events), [&](Event& e)
        {
            EventArgs args;
            args.param1 = ++i;
            args.param2 = j++;

            e(args);
        });
    }
};

int main() 
{
    network_io ni;

    ni.AddEventHandler([](EventArgs& e)
    {
        std::cout << "Param1: " << e.param1 << " Param2: " << e.param2 << "\n";
    });

    ni.AddEventHandler([](EventArgs& e)
    {
        std::cout << "The Param1: " << e.param1 << " The Param2: " << e.param2 << "\n";
    });

    ni.Process();
}
于 2013-08-19T12:24:09.910 回答