开发者

D 2.0: Class Arguments and Declaration Definitions with "new"?

开发者 https://www.devze.com 2023-03-02 16:50 出处:网络
I just took a look at the Expressions grammar for D 2.0 (NewExpression) and something caught my attention:

I just took a look at the Expressions grammar for D 2.0 (NewExpression) and something caught my attention:

NewExpression:

NewArguments ClassArg开发者_Go百科uments BaseClasslistopt { DeclDefs } 

ClassArguments:

class ( ArgumentList )

class ( )

class

What exactly are these ClassArguments and DeclDefs? Is there an example somewhere that demonstrates their use?


ClassArguments is the keyword class followed by the constructor arguments. DeclDefs are the declarations inside the class.


This syntax is to create an instance of an anonymous nested class, e.g.

import std.stdio;

void main() {
  class K {
    this() { writeln("K.__ctor"); }
  }

  auto f = new class (1, "4", 7.0) K {
    this(int a, string b, double c) {
      super();
      writefln("anon.__ctor: %s %s %s", a, b, c);
    }
  };
}

(See http://ideone.com/cA1qo.)

The above can be rewritten into the less obscure form

import std.stdio;

void main() {
  class K {
    this() { writeln("K.__ctor"); }
  }

  class AnonymousClass : K {
    this(int a, string b, double c) {
      super();
      writefln("anon.__ctor: %s %s %s", a, b, c);
    }
  }
  auto f = new AnonymousClass(1, "4", 7.0);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消