首頁 / CompScience / Programming / Languages / C_and_CPP / Name Lookup and Inheritance

Name Lookup and Inheritance

C++ Primer 4/e在Class Scope under Inheritance這個地方有一個關鍵概念:『Understanding how function calls are resolved is crucial to understanding inheritance hierarchies in C++. The following four steps are followed:

1.
Start by determining the static type of the object, reference, or pointer through which the function is called.
2.
Look for the function in that class. If it is not found, look in the immediate base class and continue up the chain of classes until either the function is found or the last class is searched. If the name is not found in the class or its enclosing base classes, then the call is in error.
3.
Once the name is found, do normal type-checking (Section 7.1.2, p. 229) to see if this call is legal given the definition that was found.
4.
Assuming the call is legal, the compiler generates code. If the function is virtual and the call is through a reference or pointer, then the compiler generates code to determine which version to run based on the dynamic type of the object. Otherwise, the compiler generates code to call the function directly.

中文版的這樣寫:『了解「函式呼叫如何被決議」對於了解C++繼承體系時十分重要。決議動作依以下四步驟進行:

  1. 首先決定呼叫者(object、reference 或 pointer)的靜態型別。
  2. 在上述class內搜尋該函式。如果沒找到,就往最接近的(immediate)base class尋找,如此上溯classes繼承鏈,直到發現該函式,或直至搜尋到最後一個class。如果都沒有發現,表示呼叫有誤。
  3. 一旦找到該名稱,就根據找到的定義式進行一般的型別檢驗(7.1.2節,p.229),檢查呼叫動作是否合法。
  4. 若呼叫合法,編譯器便產出二進制碼。如果函式是virtual,且係透過reference或pointer被呼叫,那麼編譯器產生的碼會根據物件的動態型別決定喚起那個版本。否則編譯器產生的碼會直接喚起該函式。

這個步驟可以作為checklist來coding.

Print Friendly, PDF & Email
馬上成為工作達人的Fans

About ㄚ琪

工作達人Fun Taiwan的創辦者及總編,可以在這裡更認識他。

發表迴響

你的電子郵件位址並不會被公開。 Required fields are marked *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

Scroll To Top