我想以兩種方式打印我創建的對象的信息。在C中調用「方法」OOP
OOP無關的第一種方法是調用print
函數。第二種方法類似於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->name) and free(who)
,爲什麼添加free(who->age)
會導致錯誤推廣的對象。如果我釋放存儲結構屬性的空間,是否需要free(who)
?
隨着C,你必須顯式*傳遞你的「object」*作爲方法的第一個參數,OOP沒有自動操作。當你想實現* virtual *方法時,你只需要將它作爲函數指針的成員。對於一般的方法,你只需使用正常的功能(通常命名爲' _ ()') –
'joe-> print();'。聲明是'void(* print)(struct PERSON * self);'。類型是'void(*)(struct PERSON *)'。它期望一個指向'struct PERSON'的指針。你通過它的地方?將該調用更改爲'joe-> print(joe);'。 –
順便說一句,如果你想考慮的話,直接調用'print'函數仍然是OOP。它只是一個非虛擬方法的等價物,而'joe-> print'相當於一個虛擬方法。如果你有很多這樣的方法,你可能想要創建一個const函數表,並在你的對象中只有一個指向它的指針。這也確保你不能混淆他們。 – spectras