c语言, objective code(new 1)

c struct, objective code

////////
////
typedef int (*PF_EAT) (char* food, const int cnt);
typedef int (*PF_WALK) (char* place, const int miles, int walk_miles);
typedef void (*PF_SAY) (const char* to_who, const char* words);

#define FEMALE 0
#define MALE 1

typedef struct{
    char* name;
    char sex;
    int age;
    PF_EAT eat;
    PF_WALK walk;
    PF_SAY say;
}ST_PERSON;
    
struct foods{
    char name[10];
    int cnt;
};

struct foods food_to_full[3] = {
    {"milk", 2},
    {"rice", 1},
    {"bread", 2}
};

int f_eat (char* food, const int cnt)
{

    int index = 0;
    int ret = -1;//ret = -1, nothing to eat
    
    if(food == 0){
        return -1;
    }    
    
    for(index = 0 ; index < 3; index++){
        if(strcmp(food, food_to_full[index].name) == 0 ){
            ret = (cnt >= food_to_full[index].cnt ? 0: 1);//ret = 1, not full
            
            printf("eat %d *%s %s\n", cnt, food, ret == 0 ? "is full" : "is not full");
            
            break;
        }
    }

    return ret;
}


int f_walk(char* place, const int miles, int walk_miles)
{
    int ret = 0;
    if(place == 0){
        return 0;
    }
    
    ret = (miles - walk_miles > 0) ? (miles - walk_miles) : 0;
    
    printf("walk to %s, %s", place, ret > 0 ? "is on the load" : "has arrived the location" );
    
    if(ret > 0)
    {
        printf(", remains %d miles to walk", ret);
    }
    printf("\n");
    return ret;
    
}

void f_say (const char* to_who, const char* words)
{
    printf("Hi %s, %s\n",to_who, words);
}


void person_one_day(ST_PERSON *person, struct foods* food_have, char *where, int miles, int walk_miles, char* to_who, char* words )
{
    printf("%s, %s, %d years old\n", person->name, (person->sex == MALE) ? "male" : "female", person->age);
    person->eat(food_have->name, food_have->cnt);
    person->walk(where, miles, walk_miles);
    person->say(to_who , words);
    
    printf("\n");
}
ST_PERSON Ocean = {
    .name = "Ocean",
    .sex = MALE,
    .age = 26,
    .eat = f_eat,
    .walk = f_walk,
    .say = f_say,
};

ST_PERSON Li = {
    .name = "Li",
    .sex = FEMALE,
    .age = 28,
    .eat = f_eat,
    .walk = f_walk,
    .say = f_say,
};
int main(int argc, char** argv) 
{
struct foods food_have_ocean = {"rice", 1};
struct foods food_have_li = {"milk", 1};
person_one_day(
&Li, &food_have_li, "town", 15, 11, "Lucy", "I am so tired!");
person_one_day(
&Ocean, &food_have_ocean, "town", 11, 11, "Lucy", "I am waiting for my wife");
return 0;
}

/*

>gcc person.c ; ./a.out


Li, female, 28 years old
eat 1 *milk is not full
walk to town, is on the load, remains 4 miles to walk
Hi Lucy, I am so tired!


Ocean, male, 26 years old
eat 1 *rice is full
walk to town, has arrived the location
Hi Lucy, I am waiting for my wife

*/

 

posted @ 2015-08-26 15:12  oucaijun  阅读(278)  评论(0编辑  收藏  举报
下载TeamViewer完整版 下载TeamViewer