虛函數的疑問

來源:互聯網
上載者:User

每個類中有一個虛函數表,類的執行個體中有一個指標指向類的虛函數表。定義一個類的多個對象,調試跟蹤對象中的虛函數表,不同對象的虛函數地址和內容完全一致證明了這一點。

#include <iostream><br />using namespace std;</p><p>class VirtualTest<br />{<br />public:<br />int intSlot;<br />float floatSlot;<br />bool boolSlot1;<br />bool boolSlot2; </p><p>void test0()<br />{<br />cout << "Test0" << endl;<br />}<br />virtual void test1()<br />{<br />cout << "Test1" << endl;<br />} </p><p>virtual void test2()<br />{<br />cout << "test2" << endl;<br />} </p><p>static void staticTest()<br />{ </p><p>}<br />}; </p><p>template <typename ToType, typename FromType><br />void GetMemberFuncAddr(ToType& addr,FromType f)<br />{<br />union<br />{<br />FromType _f;<br />ToType _t;<br />}ut; </p><p>ut._f = f;<br />addr = ut._t;<br />} </p><p>#define PrintMemberFuncAddr(f)/<br />{/<br />DWORD dwAddrPtr;/<br />GetMemberFuncAddr(dwAddrPtr, f);/<br />cout << #f << " = " << dwAddrPtr << endl; /<br />}</p><p>typedef unsigned long DWORD; </p><p>int main()<br />{<br />cout << "----------------------" << endl;<br />PrintMemberFuncAddr(&VirtualTest::test0);<br />PrintMemberFuncAddr(&VirtualTest::test1);<br />PrintMemberFuncAddr(&VirtualTest::test2); </p><p>PrintMemberFuncAddr(&VirtualTest::staticTest);<br />cout << "----------------------" << endl;</p><p>VirtualTest testCase1;</p><p>cout << "vfptr addr : "; PrintMemberFuncAddr( (int*)(&testCase1) );<br />cout << "vfptr-test1 : "; PrintMemberFuncAddr( (int*)*(int*)(&testCase1) );</p><p>typedef void(*MemFuncPtr)(void);<br />MemFuncPtr pFun;<br />pFun = (MemFuncPtr)*((int*)*(int*)(&testCase1));<br />pFun();//cout : Test1</p><p>pFun = (MemFuncPtr)*((int*)*(int*)(&testCase1)+1);<br />pFun();//cout : Test2</p><p>PrintMemberFuncAddr(&testCase1.staticTest);</p><p>system("PAUSE");<br />}

 

結果:

----------------------<br />&VirtualTest::test0 = 15929919<br />&VirtualTest::test1 = 15929884<br />&VirtualTest::test2 = 15929979<br />&VirtualTest::staticTest = 15930054<br />----------------------<br />vfptr addr : (int*)(&testCase1) = 1702108<br />vfptr-test1 : (int*)*(int*)(&testCase1) = 15960076<br />Test1<br />test2<br />&testCase1.staticTest = 15930054<br />請按任意鍵繼續. . .

問題:

對於類的靜態函數,通過類名和對象名獲得地址一致,上面實驗結果中:

&testCase1.staticTest = 15930054

&VirtualTest::staticTest = 15930054

 

但是對於虛函數,情況為何有差別呢?

留個記號,有時間差點資料~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.