列挙体

列挙体は, 取り得る値が制限されている型で.

ベースになる型を指定できるようになった.

enum.d

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import std.stdio;

enum SIGNAL { red = 10, yellow, green }

SIGNAL sig;

void main(){

  writefln( "sig.red = %d", sig.red );
  writefln( "sig.yellow = %d", sig.yellow );
  writefln( "sig.green = %d", sig.green );
}

enum.d の実行結果は:

[cactus:~/code_d/d_tuts]% ./enum
sig.red = 10
sig.yellow = 11
sig.green = 12

enum2.d

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import std.stdio;

enum Foo : uint { A, B, C = 10u, D }

Foo x;

void main(){
  x = Foo.A;
  writeln("x = Foo.A = ", x);

  x = Foo.B;
  writeln("x = Foo.B = ", x);

  x = Foo.C;
  writeln("x = Foo.C = ", x);

  x = Foo.D;
  writeln("x = Foo.D = ", x);
}

enum2.d の実行結果は:

[cactus:~/code_d/d_tuts]% ./enum2
x = Foo.A = 0
x = Foo.B = 1
x = Foo.C = 10
x = Foo.D = 11

enum3.d

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import std.stdio;

enum Bar { A, B, C }

Bar y;

void main(){
  y = Bar.A;
  writeln("y = Bar.A = ", y); // 0

  y = Bar.B;
  writeln("y = Bar.B = ", y); // 1

  y = Bar.C;
  writeln("y = Bar.C = ", y); // 2
}

enum3.d の実行結果は:

[cactus:~/code_d/d_tuts]% ./enum3
y = Bar.A = 0
y = Bar.B = 1
y = Bar.C = 2

Previous topic

構造体と共用体

Next topic

switch