本文介绍了匿名班的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,通常编写以下代码(例如,用于事件处理)以利用模板方法模式:

In Java, it's common to write the following (e.g. for event handling) in order to make use of the template method pattern:

abstract class SomeAbstractClass {
    public abstract void SomeFunction ();
}

//...

SomeAbstractClass obj = new SomeAbstractClass () {
    public void SomeFunction () { /* implementation */ }
};

在C ++中,将编译以下内容:

In C++, the following compiles:

class SomeAbstractClass {
    virtual void SomeFunction () = 0;
};

// ...

SomeAbstractClass * obj = new ( class : public SomeAbstractClass {
    virtual void SomeFunction () { /* implementation */ }
});

为什么人们通常不这样做?

Why don't people do this usually?

推荐答案

我认为匿名类会出现三个问题

Three problems i think occurs with anonymous class


  • 您不能将构造函数编写为类

  • 初始化器列表继承是不允许的。

  • 捕获值也很困难,最终变量只能访问。
  • li>
  • You cannot write a constructor as class doesn't have a name.
  • initializer list inheritance is not allowed.
  • capturing value is also difficult, final variable are accessible only.

这篇关于匿名班的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 22:57