私が作成したオブジェクトの情報を印刷する方法は2通りあります。COPで "メソッド"を呼び出す
OOPを何もしていない最初の方法は、print
関数を呼び出すことです。 2番目の方法はPythonのアプローチと似ています。私はjoe->print();
を使用しています、それはerror: too few arguments to function ‘joe->print’
と言います。どのようにそれを行うには?
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<string.h>
struct PERSON{
char *name;
int age;
int height;
int weight;
void (*print)(struct PERSON *self);
void (*destroy)(struct PERSON *self);
} ;
typedef struct PERSON person;
void person_print(person* who)
{
printf("Name: %s\n", who->name);
printf("Age: %d\n", who->age);
printf("Height: %d\n", who->height);
printf("Weight: %d\n", who->weight);
}
person *person_create(char *name, int age, int height, int weight)
{
person *who = malloc(sizeof(person));
assert(who != NULL);
who->name = strdup(name);
who->age = age;
who->height = height;
who->weight=weight;
who->print=&person_print;
return who;
}
void person_destroy(person *who)
{
assert(who != NULL);
free(who->name);
free(who);
}
int main(int argc, char *argv[])
{
person *joe = person_create("Joe Alex", 32, 64, 140);
person_print(joe);
//joe->print();
}
別の問題、我々は機能void person_destroy
を使用してオブジェクトを破棄するときfree(who->age)
を追加すると、エラープロモーションの原因となりますことを、なぜ、声明free(who->name) and free(who)
を理解する方法を、私は混乱があります。構造体の属性を格納するスペースを解放すれば、まだfree(who)
は必要でしょうか?
Cでは、メソッドの最初のパラメータとして「オブジェクト」*明示的に*渡す必要がありますが、OOPのオートマトンはありません。そして、* virtual *メソッドを実装したいときには、それを関数ポインタとしてメンバにする必要があります。通常の方法では、通常の関数(通常は ' _ ()') –
'joe-> print();'を使用します。宣言は 'void(* print)(struct PERSON * self);'です。タイプは 'void(*)(struct PERSON *)'です。 'struct PERSON'へのポインタを期待しています。あなたはそれをどこに渡していますか? 'joe-> print(joe);'の呼び出しを変更してください。 –
ところで、 'print'関数を直接呼び出すことは、それを考慮したい場合は、依然としてOOPです。これは非仮想メソッドと同等ですが、 'joe-> print'は仮想メソッドと同等です。そのようなメソッドがたくさんある場合は、const関数テーブルを作成し、それにオブジェクトのポインタを置くだけです。それはまたあなたがそれらを混同させることができないことを確かめます。 – spectras