クラスは参照渡し。
クラスは参照渡しなのでしょうか 値渡しなのでしょうか 確認してみよう
class Animal { private char[] name; this(){name ="Poti";} this(char[] name) { setName(name); } void setName( char[] name) { int length = name.length; this.name.length = length; this.name[0..length] = name[0..length]; } void printName() { printf(name); printf("\n"); } } |
int main() { Animal poti = new Animal("poti"); Animal taro = new Animal("taro"); poti.printName(); taro.printName(); taro = poti; taro.setName("matu"); poti.printName(); taro.printName(); return 0; } |
ということで 参照渡しです。
OverrideとVirtual
親と子の関係
class Animal { public void giveBark(){ printf("pyoro pyoro pyoro"); printf("\n\n"); } } |
class Dog : Animal { public void giveBark(){ printf("Wan Wan Wan"); printf("\n\n"); } } |
int main() { Animal Uma = new Animal(); Uma.giveBark(); Uma= new Dog(); Uma.giveBark(); return 0; } |
newUMA newDog Uma pyoro WanWan Dog noCheck WanWan
class Animal { public void giveBark(){ Barking(); } private void Barking(){ printf("pyoro pyoro pyoro"); printf("\n\n"); } } |
class Dog : Animal {s /* public void giveBark(){ Barking(); } */ private void Barking(){ printf("Wan Wan Wan"); printf("\n\n"); } } |
int main() { Animal uma = new Animal(); Dog dog = new Dog(); uma.giveBark(); dog.giveBark(); uma= new Dog(); uma.giveBark(); return 0; } |
newUMA newDog Uma pyoro pyoro Dog noCheck pyoro
class Animal { public void giveBark(){ Barking(); } private void Barking(){ printf("pyoro pyoro pyoro"); printf("\n\n"); } } |
class Dog : Animal { public void giveBark(){ Barking(); } private void Barking(){ printf("Wan Wan Wan"); printf("\n\n"); } } |
int main() { Animal uma = new Animal(); Dog dog = new Dog(); uma.giveBark(); dog.giveBark(); uma= new Dog(); uma.giveBark(); return 0; } |
newUMA newDog Uma pyoro WanWan Dog noCheck WanWan
public をprivateでoverrideしてみました。 この使い方は駄目なような気がしますが どうなのだろう。
class Animal { public void giveBark(){ Barking(); } private void Barking(){ printf("pyoro pyoro pyoro"); printf("\n\n"); } } |
class Dog : Animal { private void giveBark(){ Barking(); } private void Barking(){ printf("Wan Wan Wan"); printf("\n\n"); } } |
int main() { Animal uma = new Animal(); Dog dog = new Dog(); uma.giveBark(); dog.giveBark(); uma= new Dog(); uma.giveBark(); return 0; } |
newUMA newDog Uma pyoro pyoro Dog nocheck WanWanUmaはpyoro pyoro pyoro Dogは"WanWanWan"と吠えます。
キャストはどうなるのだろう
親と子の関係
C言語風キャストは (value) D言語風 は cast(Object)
class Animal { public void giveBark(){ Barking(); } private void Barking(){ printf("pyoro pyoro pyoro"); printf("\n\n"); } } |
class Dog : Animal { private void giveBark(){ Barking(); } private void Barking(){ printf("Wan Wan Wan"); printf("\n\n"); } } |
int main() { Animal uma = new Animal(); Animal dog = new Dog(); try{ uma.printName(); (cast(Dog)uma).giveBark(); }catch(Exception e){ printf("can't upcast"); printf("\n\n"); } dog.printName(); (cast(Dog)dog).giveBark(); return 0; } |
Upキャストは注意が必要。
あと、overrideしたくないときはどうすればよいのだろうか
戻る