1 / 9

this 的解析(補充)

this 的解析(補充). 井民全. 參考資料: C++ Primer 中文版 pp.636-641. 隱含的 this 指標. 每個 object 都有自己的一份 class data member Member function 可以 不用 dot 運算子或 arraw 運算子,便可以存取自己的 class member. Jing::Person. Jenny::Person. Name=Jing. Name=Jenny. Age=18. Age=18. 隱含的 this 指標. 例如.

penny
Download Presentation

this 的解析(補充)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. this 的解析(補充) 井民全 參考資料: C++ Primer 中文版 pp.636-641

  2. 隱含的 this 指標 • 每個 object 都有自己的一份 class data member • Member function 可以不用 dot運算子或 arraw 運算子,便可以存取自己的 class member. Jing::Person Jenny::Person Name=Jing Name=Jenny Age=18 Age=18

  3. 隱含的 this 指標 • 例如 inline void Person::setName(string MyName){ Name=MyName; } • 假設 object Jing呼叫 setName 函式, 其中 setName • 取用的 Name 為 Jing 所擁有 • object Jenny 呼叫 setName 函式, 其中取用的 Name • 為 Jenny 所擁有 奇怪! 同一份程式碼,為何一下取用 Jing 的資料 一下取用 Jenny 的資料

  4. 答案就是 this 指標 • 每個 class member function 都含有一個指標,用來指出其呼叫者 (一個 object) this • 當 object Jing 呼叫 setName() 時, this 指向的是 object Jing • 當 object Jenny 呼叫 setName(), this 就指向 object Jenny

  5. 編譯器如何實作 this • class member function的轉換 • 新增加一個額外的參數 this • 明白的使用 this 存取 class member inline void Person::move(Person* this, string MyName){ this->Name=MyName; }

  6. 編譯器如何實作 this • Member function 的呼叫動作 Jing.SetName(“Jing2”); 改成 SetName(&Jing,”Jing2”); 把object Jing 的位址放進去

  7. 何時使用 this 指標 • Copy method void Person:: copy(const Person &obj) { // 判斷是否為相同的 object 情況 if ( this ! = &obj){ Name=obj.Name; Age=obj.Age; } } 相同的東西就不用複製了

  8. 何時使用 this 指標串接呼叫 int main(){ // … myScreen.clear().move(2,2).set(‘*’).display(); } • 這一系列動作為: • 清理 screen object myscreen • 將游標移到 (2,2) • 在該位置上設定 * 並且顯示結果

  9. 何時使用 this 指標串接呼叫 myScreen.clear().move(2,2).set(‘*’).display(); • 執行順序 由左至右 • clear() 必須傳回呼叫者 (一定要this) Screen& Screen:: clear( ) { // 清螢幕的程式 return *this; } 注意: 傳回型別為 reference type

More Related