1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| #include <stdio.h> #include <malloc.h>
typedef struct myClass { void (*init)(struct myClass *self, int a, int b); //利用函数指针给变量赋值 void (*get)(struct myClass *self); int var1; //public int var2; } mC;
typedef struct myClassB //继承 { mC *parent; void (*child)(); //子类自己的方法 } mCB;
static void child_() { printf("hello\n"); }
static void init_(mC *self, int a, int b) { self->var1 = a; self->var2 = b; }
static void get_(mC *self) { printf("this -> var1:%d\n", self->var1); printf("this -> var2:%d\n", self->var2); }
int main() { mC newMyClass; newMyClass.init = init_; // 给结构体中的函数指针赋值 newMyClass.get = get_; newMyClass.init(&newMyClass, 1, 2); // 两个对外接口 newMyClass.get(&newMyClass);
printf("newMyClass2\n"); mC newMyClass2; newMyClass2.init = init_; // 给结构体中的函数指针赋值 newMyClass2.get = get_; newMyClass2.init(&newMyClass2, 3, 4); newMyClass2.get(&newMyClass2);
printf("childClass\n"); mCB childClass; childClass.parent = &newMyClass; // 直接将父类指针指向已存在的父类对象nweMyClass childClass.child = child_; childClass.child(); childClass.parent->get(childClass.parent);
printf("childClass2\n"); mCB childClass2; childClass2.parent = (mC *)malloc(sizeof(mC)); childClass2.parent->init = init_; childClass2.parent->get = get_; childClass2.parent->init(childClass2.parent, 10, 20); childClass2.parent->get(childClass2.parent); free(childClass2.parent);
printf("pointer to newMyClass2\n"); mC* ptr = &newMyClass2; ptr->get(ptr);
printf("pointer to childClass\n"); ptr = childClass.parent; //函数重载 ptr->get(ptr); }
|