赞
踩
成员变量比较好说,关键是成员函数怎么办?C中的结构体如何放一个成员函数呢?
答:可以使用函数指针。
typedef struct Base { int a; void (*print)(struct Base* this); }Base; //模仿基类构造 Base* baseCtor(int a) { Base* this = (Base*)malloc(sizeof(Base)); if(this){ this->a = a; this->print = printBase;//基类的打印函数 } return this; } //模仿基类析构 void baseDtor(Base** p){ if(*p){ free(*p); *p = NULL; } } void printBase(Base* this){ printf("Base contains: %d\n", this->a); }
继承只好通过内嵌一个其他结构体的实例实现。
typedef struct Derived { Base mbase; int b; }Derived; //模仿派生类构造 Derived* derivedCtor(int a, int b){ Derived* this = (Derived*)malloc(sizeof(Derived)); if(this){ this->mbase.a = a; this->b = b; this->mbase.print = printDerived;//派生类的打印函数 } return this; } //模仿派生类析构 void derivedDtor(Derived** p){ if(*p){ free(*p); *p = NULL; } } void printDerived(Base* this){ Derived* pderived = (Derived*)this; printf("Derived contains: %d %d\n", pderived->mbase.a, pderived->b); }
怎么实现多态?需要利用结构体中的函数指针。
如何利用?构造时将其指向不同的函数。
以下是全部代码:
#include <stdio.h> #include <malloc.h> typedef struct Base { int a; void (*print)(struct Base* this); }Base; typedef struct Derived { Base mbase; int b; }Derived; void printBase(Base* this){ printf("Base contains: %d\n", this->a); } void printDerived(Base* this){ Derived* pderived = (Derived*)this; printf("Derived contains: %d %d\n", pderived->mbase.a, pderived->b); } Base* baseCtor(int a) { Base* this = (Base*)malloc(sizeof(Base)); if(this){ this->a = a; this->print = printBase; } return this; } void baseDtor(Base** p){ if(*p){ free(*p); *p = NULL; } } Derived* derivedCtor(int a, int b){ Derived* this = (Derived*)malloc(sizeof(Derived)); if(this){ this->mbase.a = a; this->b = b; this->mbase.print = printDerived; } return this; } void derivedDtor(Derived** p){ if(*p){ free(*p); *p = NULL; } } int main(int argc, char* argv[]) { Derived* pd = derivedCtor(1,2); Base* pb = (Base*)pd;//基类指针指向派生类对象 pb->print(pb);//调用的是派生类的打印函数 derivedDtor(&pd); return 0; }
输出:

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。