D言語によるオブジェクト指向プログラミング

D言語では、構造体は値型(value type)、クラスは参照型(reference type)です。

 

robot.d

import std.stdio;
import std.typecons;

class Robot {
private:
  Tuple!(real, real) position;

public:
  this(real x = 0, real y = 0) {
    position[0] = x;
    position[1] = y;
  }

  void x(real x) {position[0] = x;}

  void y(real y) {position[1] = y;}

  real x() const {return position[0];}

  real y() const {return position[1];}

  void move(real dx, real dy) {
    position[0] += dx;
    position[1] += dy;
  }

  void print() const {
    writefln("x = %f", position[0]);
    writefln("y = %f", position[1]);
  }
}

 

main.d

import robot;
import std.stdio;

void main() {
  auto robot1 = new Robot;
  robot1.x(1);
  robot1.y(1);
  robot1.move(1, 1);
  writefln("x = %f", robot1.x);
  writefln("y = %f", robot1.y);

  Robot[] robot2 = [new Robot, new Robot];
  foreach (r; robot2) {
    r.move(1, 1);
    r.print();
  }

  uint n = 10;
  Robot[] robot3 = new Robot[n];
  for (uint i = 0; i < robot3.length; i++) {
    robot3[i] = new Robot;
    robot3[i].move(i, i);
    robot3[i].print();
  }
}

 

コンパイル方法1(robot.d, main.d → program.exe)

> dmd robot.d main.d -ofprogram.exe

 

コンパイル方法2(*.d → program.exe)

> mingw32-make -f makefile.txt

 


DC = C:¥dmd¥windows¥bin¥dmd.exe
SOURCES = $(wildcard *.d)
PROGRAM = program.exe
$(PROGRAM): $(SOURCES)
	$(DC) $^ -of$@