问题
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 */ }
};
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?
回答1:
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.
来源:https://stackoverflow.com/questions/18171684/anonymous-classes