版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/jwzhangjie/article/details/27959577
一、函数指针
//
// main.c
// L01Helloc
//
// Created by zj on 14-6-1.
// Copyright (c) 2014年 zj. All rights reserved.
//
#include <stdio.h>
void sayHello(){
printf("Helloc C
");
}
void sayHello1(int i){
printf("Hello C %d
",i);
}
int main(int argc, const char * argv[])
{
void (*p)();
void (*p1)(int i);
p = sayHello;
p1 = sayHello1;
p();
p1(98);
return 0;
}
二、Typedefkeyword
//
// main.c
// L01Helloc
//
// Created by zj on 14-6-1.
// Copyright (c) 2014年 zj. All rights reserved.
//
#include <stdio.h>
typedef struct {
int age;
} People;
void sayHello(){
printf("Helloc C
");
}
//代表返回值为void ,无传入參数的函数
typedef void (*Func)();
int main(int argc, const char * argv[])
{
People p;
p.age = 13;
Func f = sayHello;
f();
return 0;
}
三、面向对象
//
// main.c
// L01Helloc
//
// Created by zj on 14-6-1.
// Copyright (c) 2014年 zj. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
//Object begin>>>>>>>>>
#define ObjectField void(*onDelete)(void*);
typedef struct Object{
ObjectField
} Object;
#define ObjectCreate(TYPE) malloc(sizeof(TYPE))
#define ObjectDelete(obj) {
obj->onDelete(obj);
free(obj);
}
void ObjectOnDelete(void *obj){
printf("Object on delete
");
}
Object* ObjectInit(Object *obj){
obj->onDelete = ObjectOnDelete;
return obj;
}
//Object end<<<<<<<<<<<<<<<<<<<<<
typedef struct {
ObjectField
int age;
void(*sayHello)();
} People;
void PeopleSayHelloc(){
printf("Hello
");
}
void PeopleOnDelete(void *p){
ObjectOnDelete(p);
printf("People on delete
");
}
People* PeopleInit(People *p, int age){
ObjectInit((Object *)p);
p->age = age;
p->sayHello = PeopleSayHelloc;
p->onDelete = PeopleOnDelete;
return p;
}
int main(int argc, const char * argv[])
{
People *p = PeopleInit(ObjectCreate(People), 20);
p->sayHello();
ObjectDelete(p);
return 0;
}