一、C语言实现继承
原理:结构体组合类
typedef struct Base
{
int b_val = 0;
void show()
{
printf("b_val:%d\n", b_val);
}
}Base;
typedef struct Son
{
Base base;
int s_val = 10;
void show()
{
printf("s_val:%d\n", s_val);
}
}Son;
int main()
{
Son s;
s.show();
s.base.show();
return 0;
}
二、C语言实现多态
(1)静态多态
原理:使用宏实现 静态多态:函数重载、运算符重载
#define SUM(A,B) (A)+(B)
int main()
{
printf("%d\n", SUM(10, 20));
string s1("hello");
string s2("world");
cout << SUM(s1, s2) << endl;
return 0;
}
(2)动态多态
注意:当公有继承的基类中不存在虚函数时,构建的对象内存中不含有__vfptr指针 原理:继承前提下,使用函数指针、虚表指针、理解构建虚函数表的过程
在实现动态多态前,我们先看看C++提供给我们的类结构是怎样的,以下面代码为例
class Base
{
private:
int b_val;
public:
Base(int x = 0): b_val(x){}
virtual void fun()
{
cout << "b_val:"<< b_val << endl;
}
};
class Son : public Base
{
private:
int s_val;
public:
Son(int x = 0) : Base(x), s_val(x + 10) {}
virtual void fun()
{
cout << "s_val:" << s_val << endl;
}
};
int main()
{
Son s;
return 0;
}
s对象内存结构: 实现代码:
#include<iostream>
using namespace std;
typedef struct vftable
{
void (*show)(void*);
}vftable;
typedef struct Base
{
vftable* __vfptr;
int b_val = 0;
}Base;
typedef struct Son
{
Base base;
int s_val = 10;
}Son;
void ShowBase(void* th)
{
Base* bs = (Base*)th;
printf("b_val:%d\n", bs->b_val);
}
void ShowSon(void* th)
{
Son* ss = (Son*)th;
printf("s_val:%d\n", ss->s_val);
}
vftable base_vftable = { ShowBase};
vftable son_vftable = { ShowSon };
Base* create_Base(int val)
{
Base* tmp = (Base*)malloc(sizeof(Base));
memset(tmp, 0, sizeof(Base));
tmp->__vfptr = &base_vftable;
tmp->b_val = val;
return tmp;
}
Son* create_Son(int val)
{
Son* tmp = (Son*)malloc(sizeof(Son));
memset(tmp, 0, sizeof(Son));
tmp->base.__vfptr = &son_vftable;
tmp->base.b_val = 0;
tmp->s_val = val;
return tmp;
}
int main()
{
Son* sp = create_Son(10);
Base* bp = (Base*)sp;
bp->__vfptr->show((void*)sp);
free(sp);
bp = NULL;
sp = NULL;
return 0;
}
结果:使用基类指针成功调用派生类成员方法
对应内存结构:
参考文章: C语言实现多态
|