インスタンス変数へのダイレクト代入
コレ前も書いたかな?
次のバージョンくらいから使えるようになる機能です。
こんな感じのモノを書いたことはないでしょうか?
struct Enemy{ float x; float y; float velx; float vely; float power; float life; Enemy(float ax, float ay, float avelx = 0, float avely = 0, float apower = 0, float alife = 0){ x = ax; y = ay; velx = avelx; vely = avely; power = apower; life = alife; // 他の初期化省略 } // 後のメンバ省略 }; Enemy e(5, 5, 0, 0, 10, 1);
みたいな感じで、受取った引数をインスタンス変数にただそのまま設定していくだけのコンストラクタ。
これはただの作業なのですごい退屈なんですよね。
これをある程度軽減する仕様です。
Enemy: class{ + _x; + _y; + _velx; + _vely; + _power; + _life; initialize: method(_x, _y, _velx: 0, _vely: 0, _power: 0, _life: 0){ //後の初期化省略 } // 後のメンバ省略 } e: Enemy(5, 5, 0, 0, 10, 1); e.power.p; //=> 10
このように、メソッドの引数にインスタンス変数を書くと、渡された引数が直接代入される機能です。
method(_x, _y, _velx: 0, _vely: 0, _power: 0, _life: 0){
は
method(x, y, velx: 0, vely: 0, power: 0, life: 0){ _x = x; _y = y; _velx = velx; _vely = vely; _power = power; _life = life
と記述したのと全く一緒になります。
便利、ですよね?