多态 oc c++ 与oc category

多态是函数调用的动态绑定技术;

c++动态绑定依赖于this指针与虚函数表。

虚函数表的排序规则:

1)虚函数按照其声明顺序放于表中。

2)父类的虚函数在子类的虚函数前面。

3)如果子类重写了父类的虚函数,覆盖的函数被放到了虚表中原来父类虚函数的位置。

4)子类虚函数中使用父类同名函数:

 

class B
{
public:
virtual void f()
{ cout << "B::f()" << endl;}
};
class B1 : public B
{
public: virtual void f() {B::f(); //这个是如何取到地址的?
   cout << "B1::f()" << endl;}
};

 

oc中的多态依赖于objc_msgSend: 

When a message is sent to an object, the messaging function follows the object’s isa pointer to the class structure where it looks up the method selector in the dispatch table. If it can’t find the selector there, objc_msgSend follows the pointer to the superclass and tries to find the selector in its dispatch table.

先通过isa查找本类的结构,再通过superclass查找父类的结构;

 

oc的类别:

在进程启动时,类被加载到内存时,类别的所有方法会放置在类的原有方法的前面,从而隐藏掉原有的同名方法(结构中会保留两个函数)。通过技术手段可以在类别中调用原来的方法。

 

posted @ 2016-10-31 17:34  zzfx  阅读(212)  评论(0编辑  收藏  举报