码迷,mamicode.com
首页 > 编程语言 > 详细

C实现C++的多态性,呵呵......

时间:2015-01-11 19:02:47      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:

有以下两个C++类:

class Base {
public:
   Base(int a, int b) : m_a(a), m_b(b) {}
   virtual void Func1();
   virtual int Func2();
private:
   int m_a, m_b;
}

class Derived : public Base {
public:
   Derived(int a, int b, double d) : Base(a, b), m_d(d) {}
   virtual int Func2();
private:
   double m_d;
}

模拟通常C++编译器的实现机制,用C语言给出Base、Derived的定义,并实现两个类的创建代码:

typedef void** VtblPtr; 
struct base_t
{
   VtblPtr _vtbl;
   int m_a;
   int m_b;
};

struct derived_t
{
   VtblPtr _vtbl;
   int m_a;
   int m_b;
   double m_d;
};

//new Base时
base_t * pBase = malloc( sizeof(base_t) );
pBase -> _vtbl[0] = & _base_t_Func1;
pBase -> _vtbl[1] = & _base_t_Func2;
_base_t_Base( pBase, a, b ); 

//new Derived时
derived_t * pDerived = malloc(sizeof(derived_t) );
pDerived -> _vtbl[0] = &_base_t_Func1;
pDerived -> _vtbl[1] = &_derived_t_Func2;

//derived_t的构造函数
void _derived_t_Derived( derived_t*pDerived, int a, int d)
{
   _base_t_Base( (base_t*)pDerived, a, b);
   pDerived -> m_d = d;
}

 

C实现C++的多态性,呵呵......

标签:

原文地址:http://www.cnblogs.com/geekpaul/p/4216904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!