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.

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *