通过一个例子来说明 吧:
一:无继承
class TestA
{
public:
TestA();
~TestA();
virtual void v_ test_print()
{
cout<<"virtual method test"<<endl;
cout<<"the value is :"<<m_nTestValue<<endl;
}
void test_print()
{
cout<<"normal method test"<<endl;
cout<<"the value is :"<<m_nTestValue<<endl;
}
private:
int m_nTestValue;
};
TestA * pObj=new TestA();
pObj->test_print();
pObj->v_test_print();
*pObj指向的对象的内存结构是:
vtbl(4bytes)
m_nTestValue(4bytes)
我们可以做一个实验:
1:内存结构
char * pTmp=new char[sizeof(TestA)];
memcpy(pTmp,pObj,sizeof(TestA));
TestA * pCloneObj=reinterpret_cast<TestA *>(pTmp);
pClone->v_test_print();
pClone->test_print();
2:函数调用:
(1)normal method:
pObj->test_print()的等效汇编代码(vc)
__asm{
mov ecx,pObj
call TestA::test_print
};
(2)virtual method:
pObj->v_test_print()的等效汇编代码(vc)
__asm{
mov ecx,pObj
mov eax,[ecx] //取得vtbl指针
mov eax,[eax]
call eax
}
二:多继承
与无继承相仿:
例如:
class TestB:pubic TestA
{
......
};
TestB objB;
objB的结构是:
class TestA
class TestB
一:无继承
class TestA
{
public:
TestA();
~TestA();
virtual void v_ test_print()
{
cout<<"virtual method test"<<endl;
cout<<"the value is :"<<m_nTestValue<<endl;
}
void test_print()
{
cout<<"normal method test"<<endl;
cout<<"the value is :"<<m_nTestValue<<endl;
}
private:
int m_nTestValue;
};
TestA * pObj=new TestA();
pObj->test_print();
pObj->v_test_print();
*pObj指向的对象的内存结构是:
vtbl(4bytes)
m_nTestValue(4bytes)
我们可以做一个实验:
1:内存结构
char * pTmp=new char[sizeof(TestA)];
memcpy(pTmp,pObj,sizeof(TestA));
TestA * pCloneObj=reinterpret_cast<TestA *>(pTmp);
pClone->v_test_print();
pClone->test_print();
2:函数调用:
(1)normal method:
pObj->test_print()的等效汇编代码(vc)
__asm{
mov ecx,pObj
call TestA::test_print
};
(2)virtual method:
pObj->v_test_print()的等效汇编代码(vc)
__asm{
mov ecx,pObj
mov eax,[ecx] //取得vtbl指针
mov eax,[eax]
call eax
}
二:多继承
与无继承相仿:
例如:
class TestB:pubic TestA
{
......
};
TestB objB;
objB的结构是:
class TestA
class TestB