简体   繁体   English

匿名课程

[英]Anonymous classes

In Java, it's common to write the following (eg for event handling) in order to make use of the template method pattern: 在Java中,为了使用模板方法模式,编写以下内容(例如,用于事件处理)是很常见的:

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

//...

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

In C++, the following compiles: 在C ++中,以下编译:

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 我认为有三个问题出现在匿名类中

  • 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. 捕获值也很困难,最终变量只能访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM