c语言结构体和对象,C语言用结构体和指针实现面向对象编程

结构体和指针,C语言的灵魂。面向对象我就不班门弄斧解释了。

首先,一个结构体:

struct Person

{

char* name;

int age;

int height;

int weight;

}

那么“造人”吧:

struct Person* Create_person(const char* name,int age,int height,int weight)

{

struct Person* who = malloc(sizeof(struct Person));

who->name=name;

who->age=age;

who->height=height;

who->weight=weight;

return who;

}

怎么“杀人”呢?

void Destroy_person(struct Person* who)

{

free(who->name); // be carefull

free(who);

}

输出“人”的信息:

void Print_person(struct person* who)

{

printf("Name:%s",who->name);

printf("Age:%d",who->age);

printf("height:%d",who->height);

printf("weight:%d",who->weight);

}

最后测试一下:

int main(int argc, char *argv[])

{

// make two people structures

struct Person *joe = Person_create(

"Joe Alex", 32, 64, 140);

struct Person *frank = Person_create(

"Frank Blank", 20, 72, 180);

// print them out and where they are in memory

printf("Joe is at memory location %p:\n", joe);

Person_print(joe);

printf("Frank is at memory location %p:\n", frank);

Person_print(frank);

// make everyone age 20 years and print them again

joe->age += 20;

joe->height -= 2;

joe->weight += 40;

Person_print(joe);

frank->age += 20;

frank->weight += 20;

Person_print(frank);

// destroy them both so we clean up

Person_destroy(joe);

Person_destroy(frank);

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值