2017-07-21 55 views
2

我想以兩種方式打印我創建的對象的信息。在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)

+2

隨着C,你必須顯式*傳遞你的「object」*作爲方法的第一個參數,OOP沒有自動操作。當你想實現* virtual *方法時,你只需要將它作爲函數指針的成員。對於一般的方法,你只需使用正常的功能(通常命名爲' _ ()') –

+3

'joe-> print();'。聲明是'void(* print)(struct PERSON * self);'。類型是'void(*)(struct PERSON *)'。它期望一個指向'struct PERSON'的指針。你通過它的地方?將該調用更改爲'joe-> print(joe);'。 –

+1

順便說一句,如果你想考慮的話,直接調用'print'函數仍然是OOP。它只是一個非虛擬方法的等價物,而'joe-> print'相當於一個虛擬方法。如果你有很多這樣的方法,你可能想要創建一個const函數表,並在你的對象中只有一個指向它的指針。這也確保你不能混淆他們。 – spectras

回答

2

1部分:

你在使用print沒有必要的參數錯誤的意見進行了說明。

你必須知道,有在C.沒有出現神奇隱形this指針沒有OO的東西...

如果你想使用這樣的東西,你通過了!故事結局。 ;)

2部分:

我建議你搶初學者公司的C書,並檢查有關動態內存使用情況的章節。

還有一個問題讓我感到困惑,當我們使用functionvoid person_destroy銷燬對象 ,如何理解語句 自由(如 - >名)和free(誰),爲什麼

非常簡單的規則: 已分配的每塊內存必須再次釋放。

person *who = malloc(sizeof(person)); // Memory block #1 
... 
who->name = strdup(name);    // Memory block #2 

secod爲字符串的副本分配內存並將地址分配給who->name

添加免費(who-> age)會導致錯誤提升。

由於who->age不是指針,但一個整數,當您使用它作爲參數調用free當然,你會得到一個錯誤。 錯誤消息可能會告訴您有關該類型的不匹配。

如果我釋放空間存儲 這個結構的屬性,會自由(誰)仍然有必要?

當然。 free應該如何知道它傳遞的內存塊的入口? 在C中沒有自動調用的析構函數