【C++】深度探索C++物件模型讀書筆記--Function(The Semantics of Function)

來源:互聯網
上載者:User

標籤:

1. Nonstatic member function(非靜態成員函數)的調用方式

  編譯器會將”member 函數執行個體“轉換為對等的”nonmember函數執行個體“。

  對於非靜態成員函數

float Point3d::magnitude3d() const{...}

  轉換步驟如下:

  1. 改寫函數的signature(意指:函數原型)以安插一個額外的參數到member function中,用以提供一個存取管道,使class object得以將此函數調用。該額外參數被稱為this指標:

//non-const nonstatic member的擴張過程Point3d Point3d::magnitude(Point3d *const this)如果是member function 是const,則變成://const nonstatic member的擴張過程: Point3d Point3d::magnitued(const Point3d *const this)

  2. 將每一個”對nonstatic data member的存取操作”改為經由this指標來存取:

  3.將member function重新寫成一個外部函數。將函數名稱經過“mangling”處理,使它在程式中成為獨一無二的詞彙:

extern magnitude_7Point3dFv(    register Point3d *const this);

  現在這個函數已經被轉換好了,而其每一個叫用作業也都必須被轉換。於是:

1 obj.magnitude();2 變成了:3     magnitude_7Point3dFv(&obj);4  而5     ptr->magnitued();6 變成了:7     magnitude_7Point3dFv(ptr);

 

2. Virtual Member Functions(虛擬成員函數)

使用指標調用虛擬函數:

  如果normalize()是一個virtual member function,那麼以下的調用:

ptr->normalize();

  將會被內部轉化為:

(*ptr->vptr[1])(ptr);

  其中:

  •   vptr表示由編譯器產生的指標,指向virtual table。它被安插在每一個“聲明有(或繼承自)一個或多個virtual functions”的class object中
  •   1是virtual table slot 的索引值,關聯到normalize()函數。
  •   第二個ptr表示this指標。

  

使用類對象調用虛擬函數:

  使用類對象調用虛擬函數,其解析方式和非靜態成員函數一樣。對於上一節中的normalize()函數。調用方式最終被解析為:

normalize_7Point3dFv(&obj);

 

3. Static member Function(靜態成員函數)

  1.靜態成員函數的主要特性:

  •   它不能直接存取class中的nonstatic members
  • 它不能被聲明為cosnt、volatile或virtual
  • 它不需要經由class object才被調用--雖然大部分時候它是這樣被調用的

 

  2. 取一個靜態成員函數的地址,獲得的將是其在記憶體中的位置,也就是其地址。由於static member function沒有this指標,所以其地址類型並不是一個“指向class member function的指標”,而是一個“nonmember函數指標“

【C++】深度探索C++物件模型讀書筆記--Function(The Semantics of Function)

聯繫我們

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