Cのお勉強 Cでオブジェクト指向っぽく
Cを久しぶりにちょっと勉強してみようと思い立って(これはおそらく受験勉強からの逃避行動)、どうせ勉強するならCでオブジェクト指向っぽくクラスみたいなものを作るにはどうしたらいいかとか考えながらやってみました。
$main.c$ #include <stdio.h> #include "animal.h" #include "dog.h" int main(){ struct animal* dog; struct animal* animal; dog = dog_new( "Pochi" ); dog->bark(dog); dog->destroy(dog); animal = animal_new( "Unknown animal" ); animal->bark(animal); animal->destroy( animal ); return 0; }; $animal.h$ #ifndef ANIMAL_H #define ANIMAL_H struct animal{ // methods void (*destroy)( struct animal* ); void (*bark) ( struct animal* ); // properties char* name; }; struct animal *animal_new( char* ); void animal_destroy( struct animal* ); void animal_bark ( struct animal* ); #endif $animal.c$ #include <stdio.h> #include <stdlib.h> #include "animal.h" struct animal *animal_new( char* name ){ struct animal *this; this = ( struct animal* )malloc(sizeof(struct animal)); // method this->destroy = animal_destroy; this->bark = animal_bark; // properties this->name = name; return this; }; void animal_destroy( struct animal* this ){ printf("%s died.\n", this->name); free( this ); }; void animal_bark( struct animal* this ){ printf("%s barks '%s'.\n", this->name, "Buhi! Buhi!"); }; $dog.h$ #ifndef DOG_H #define DOG_H #include "animal.h" struct animal *dog_new( char* name ); void dog_bark( struct animal* ); #endif $dog.c$ #include <stdio.h> #include <stdlib.h> #include "animal.h" #include "dog.h" struct animal *dog_new( char* name ){ struct animal *this; this = animal_new( name ); // method this->bark = dog_bark; return this; }; void dog_bark( struct animal* this ){ printf("%s barks '%s'.\n", this->name, "Wan! Wan!"); };
と、こんな感じに書いてみました。 実行結果は下のような感じです。
Pochi barks 'Wan! Wan!'. Pochi died. Unknown animal barks 'Buhi! Buhi!'. Unknown animal died.
これはこれでいいんですが、継承してる意味がいまいちないんですよね。
構造体は動的に拡張はできないみたい(当然?)なので、継承してプロパティーやメソッドを新たに定義できません。
barkを置き換えることはできるのですが。
それなら、struct dogを作ればよいじゃないかということになるのですが、それだと親クラスのメソッドは引数にstruct animal*を要求しているので、うまくいかなくなるんです。
どうしたものか……。 これを考えるのはけっこう勉強になるんじゃないか>自分。 C++使えよlol