1. 程式人生 > >C語言模擬C++類

C語言模擬C++類

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct class
{
    int value;
    struct class *p_next;

    void (*init)   (struct class *this);
    void (*destroy)(struct class *this);

    void (*set_value)(struct class *this, int value);
    int  (*get_value)(struct
class *this); }; struct class * create_instance(); void destroy_instance(struct class *p_instance); /******** * 定義 * ********/ void init(struct class *this) { this->value = 0; this->p_next = NULL; } void destroy(struct class *this) { // TODO 釋放內部成員 } void set_value(struct class *this
, int value) { this->value = value; } int get_value(struct class *this) { return this->value; } struct class * create_instance() { struct class *p_instance = (struct class *)malloc(sizeof(struct class)); memset(p_instance, 0, sizeof(struct class)); p_instance->init = init; p_instance->destroy = destroy; p_instance->set_value = set_value; p_instance->get_value = get_value; p_instance->init(p_instance); return
p_instance; } void destroy_instance(struct class *p_instance) { p_instance->destroy(p_instance); free(p_instance); } int main() { struct class *p_instance = create_instance(); //p_instance->set_value(p_instance, 5); printf("%d\n", p_instance->get_value(p_instance)); destroy_instance(p_instance); return 0; }