虛函數表 & 指標

來源:互聯網
上載者:User

    今天看了hairetz轉載的一篇關於虛函數表的文章,的確很好

    http://blog.csdn.net/hairetz/archive/2009/04/29/4137000.aspx

    然後對其中的一些問題又重新複習了下,通過下面的代碼來解釋

#include<iostream><br />using namespace std;</p><p>class Base<br />{<br />public: </p><p>virtual void f()<br />{<br />cout << "Base::f" << endl;<br />} </p><p>virtual void g()<br />{<br />cout << "Base::g" << endl;<br />} </p><p>virtual void h()<br />{<br />cout << "Base::h" << endl;<br />} </p><p>};</p><p>typedef void(*Fun)(void);</p><p>int main()<br />{<br />Base b;<br />Fun pFun = NULL;</p><p>cout<<(int*)*(int*)(&b)<<endl<<endl; //虛函數表的首地址</p><p>//注意:虛函數表訪問的時候,自己本身有個地址,然後他儲存的也是地址(指向函數的地址)</p><p>cout<<endl;<br />cout<<(Fun)*((int*)*(int*)(&b)+0)<<endl; //虛函數表裡儲存的函數的地址 </p><p>cout<<(Fun)*((int*)*(int*)(&b)+1)<<endl; </p><p>cout<<(Fun)*((int*)*(int*)(&b)+2)<<endl; </p><p>cout<<endl;<br />cout<<(int *)*((int*)*(int*)(&b)+0)<<endl; </p><p>cout<<(int *)*((int*)*(int*)(&b)+1)<<endl; </p><p>cout<<(int *)*((int*)*(int*)(&b)+2)<<endl; </p><p>cout <<endl;<br /> cout <<(Fun)((int*)*(int*)(&b)+0) <<endl; // 虛函數表裡自己本身的地址 </p><p> cout <<(Fun)((int*)*(int*)(&b)+1) <<endl; </p><p> cout <<(Fun)((int*)*(int*)(&b)+2) <<endl; </p><p> cout <<endl;<br /> cout <<(int *)((int*)*(int*)(&b)+0) <<endl; </p><p> cout <<(int *)((int*)*(int*)(&b)+1) <<endl; </p><p> cout <<(int *)((int*)*(int*)(&b)+2) <<endl; </p><p>return 0;<br />}</p><p>/*</p><p>0046F01C //虛函數表的首地址</p><p>0040122B //虛函數表裡儲存的函數的地址<br />004010AF<br />004012AD</p><p>0040122B<br />004010AF<br />004012AD</p><p>0046F01C //虛函數表裡自己本身的地址<br />0046F020<br />0046F024</p><p>0046F01C<br />0046F020<br />0046F024<br />Press any key to continue</p><p>*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.