复习三:C的OOP-多态

#pragma once
/*super.h*/
typedef 
int  (*getValue)(void *);
typedef  
struct CSuper_t{
 
void  *body;
 getValue   GetValue;
}
CSuper;

#define Super_GetValue(n)  (n->super.GetValue)(n->super.body);

 

 

/*sub1.h*/
#include 
"super.h"
/* クラス宣言 */
typedef 
struct CSub1_t{
 CSuper super;
 
int    value1;
}
CSub1;

/*初期化関数*/
extern void  Sub1_Initial(CSub1*);
/*ゲット関数*/
extern int Sub1_GetValue(CSub1*);

 

 

 

/*sub2.h*/
#include 
"super.h"
/* クラス宣言 */
typedef 
struct CSub2_t{
 CSuper super;
 
int    value2;
}
CSub2;

/*初期化関数*/
extern void  Sub2_Initial(CSub2*);
/*ゲット関数*/
extern int Sub2_GetValue(CSub2*);

 

/*sub1.c*/
#include 
"sub1.h"
void  Sub1_Initial(CSub1* this)

 
this->super.body = this;
 
this->super.GetValue = Sub1_GetValue;
 
this->value1 = 100;
 
//return &(this->super);
}

int Sub1_GetValue(CSub1* this)
{
 
return this->value1;
}

 

 

/*sub2.h*/
#include 
"super.h"
/* クラス宣言 */
typedef 
struct CSub2_t{
 CSuper super;
 
int    value2;
}
CSub2;

/*初期化関数*/
extern void  Sub2_Initial(CSub2*);
/*ゲット関数*/
extern int Sub2_GetValue(CSub2*);

 

 

/*sub2.c*/
#include 
"sub2.h"
void  Sub2_Initial(CSub2* this)

 
this->super.body = this;
 
this->super.GetValue = Sub2_GetValue;

 
this->value2 = 200;
 
//return &(this->super);
}

int Sub2_GetValue(CSub2* this)
{
 
return this->value2;
}

 

 

/*main.c*/
#include 
"sub1.h"
#include 
"sub2.h"
#include 
"super.h"
CSub1 mSub1;
CSub1 
*pSub1;
CSub2 mSub2;
CSub2 
*pSub2;
CSuper   
*pSuper;
void main(){
    
int s1=0;
    
int s2=0;
    pSub1 
= &mSub1;
    pSub2 
= &mSub2;
    Sub1_Initial(pSub1);
    s1 
= Super_GetValue(pSub1);
    Sub2_Initial(pSub2);
    s2 
= Super_GetValue(pSub2);
}

 

 super是IF类,有一个函数指针成员,还有就是宏,就是用这个宏实现多态的哦

sub在初期化的时候要给继承super的函数指针成员一个函数地址

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的横打

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值