c语言实现c++的继承和多态

继承和多态是C++的特性,它C语言没有这个特性。

C++的三大特性:继承,多态,封装。

继承:分为公有(public)继承,私有(private)继承,保护(protected)继承。

用struct来模拟实现,因为struct在C和C++中都能可以使用,在C中称为结构体在C++中称为类,但他们的原理是一样的,又因为struct的限定符默认是公有的,在C中没有限定符这个概念,所以用c语言只能实现成公有继承


#include<iostream>
#include<stdio.h>


using namespace std;
//
//实现继承
typedef void(*ss)();
struct A
{
ss s;
int a;
};
//struct B
//{
// struct A _a ;
// int b;
//};
//void fun()
//{
// printf("father is ss");
//}
//int main()
//{
// struct A _a;
// struct B _b;
// _b._a.a=1;
// _b._a.s=fun;
// _b.b=2;
// printf("child->father:%d",_b._a.a);
// _b._a.s();
// system("pause");
// return 0;
//}
//实现多态
typedef void(*SS)();


struct A
{
SS s;
int d;
};
struct B
{
struct A _a;
};
void printfc()
{
printf("father....\n");
}
void printfd()
{
printf("child...\n");
}
int main()
{
struct A a;
struct B b;
struct A* a1;
b._a.d=1;
a.s=printfc;
b._a.s=printfd;
a1=&a;
a1->s();
a1=(struct A *)&b;
a1->s();
system("pause");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值