構造体と共用体

C の構造体/共用体と同様に, D 言語の構造体/共用体も値型である:

struct Foo{
  int a;
  char[] t;
}
Foo x;

union Bar{
  int a;
  double b;
}
Bar y;

構造体と共用体は値型.

関数定義と同様に最後にセミコロン (;) は不要.

C 形式の宣言は不正:

struct Foo x; // error
union Bar y; // error

構造体も参照のこと.

struct_union.d

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import std.stdio;

/* エラー (not like C)
struct Moivie{
  int year;
  string title;
}movie1;
*/

/* エラー (not like C)
union Book{
  int year;
  string title;
}book1;
*/

struct Movie{
  int year;
  string title;
}

Movie movie1;
Movie* pMovie;

union Book{
  int year;
  string title;
}

Book book1;

void main(){
  movie1.year = 2010;
  movie1.title = "Biohazard IV";

  pMovie = &movie1; // 構造体へのポインタ

  book1.year = 2010;
  book1.title = "Love Story";

  writeln( "movie1.year = ", (*pMovie).year );
  writeln( "movie1.title = ", pMovie.title );
/*
  pMoive->year が使えない.
  (*pMovie).year と pMoive.year が同じである.
*/

  writeln( "book1.year = ", book1.year );
  writeln( "book1.title = ", book1.title );
}

struct_union.d の実行結果は:

[cactus:~/code_d/d_tuts]% ./struct_union
movie1.year = 2010
movie1.title = Biohazard IV
book1.year = 10
book1.title = Love Story

Previous topic

関数

Next topic

列挙体