Created
December 16, 2008 10:29
-
-
Save hitode909/36414 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
/* human class (structure) | |
This structure has pointers to methods. | |
*/ | |
typedef struct _human{ | |
char* _name; | |
int _age; | |
/* get */ | |
char* (*get_name)(struct _human* self); | |
int (*get_age)(struct _human* self); | |
/* set */ | |
int (*set_name)(struct _human* self, char* name); | |
int (*set_age)(struct _human* self, int age); | |
/* methods */ | |
int (*greece)(struct _human* self); | |
struct _human* (*delete)(struct _human* self); | |
} human; | |
/* return name */ | |
char* _human_get_name(human* self){ | |
if(!self) return NULL; | |
return self->_name; | |
} | |
/* return age */ | |
int _human_get_age(human* self){ | |
if(!self) return -1; | |
return self->_age; | |
} | |
/* set name | |
This method doesn't allow overwrite of name. | |
*/ | |
int _human_set_name(human* self, char* name){ | |
if(!self) return 0; | |
if(self->_name){ | |
fprintf(stderr, "WARNING: You can set name once.\n"); | |
return(1); | |
}else{ | |
self->_name = name; | |
} | |
return(0); | |
} | |
/* set age */ | |
int _human_set_age(human* self, int age){ | |
if(!self) return(0); | |
self->_age = age; | |
return(1); | |
} | |
/* print greeting message */ | |
int _human_greece(human* self){ | |
if(!self) return(0); | |
printf("Hi, I'm %s.\n", self->get_name(self)); | |
printf("I'm %d years old.\n", self->get_age(self)); | |
return(1); | |
} | |
/* delete allocated memory */ | |
human* _human_delete(human* self){ | |
if(!self) return(NULL); | |
free(self); | |
return NULL; | |
} | |
/* constructer */ | |
human* newhuman(char* name, int age){ | |
/* allocate memory */ | |
human* self; | |
self = malloc(sizeof(human)); | |
self->_age = -1; | |
self->_name = NULL; | |
/* link functions */ | |
self->get_name = _human_get_name; | |
self->get_age = _human_get_age; | |
self->set_name = _human_set_name; | |
self->set_age = _human_set_age; | |
self->greece = _human_greece; | |
self->delete = _human_delete; | |
/* store member functions */ | |
self->set_name(self, name); | |
self->set_age(self, age); | |
/* return self */ | |
return(self); | |
} | |
/* main */ | |
int main(void){ | |
human *taro; | |
taro = newhuman("Taro", 18); | |
taro->greece(taro); | |
taro->set_age(taro, 19); | |
taro->greece(taro); | |
taro->set_name(taro, "Toshiko"); | |
taro->greece(taro); | |
taro = taro->delete(taro); | |
// cannot call | |
// taro->get_name(taro); | |
return(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment