hce_nsysu
111年
計算機概論與程式設計
第 69 題
`Student` is a base class and `TA` is a derived class, with a redefined non-`virtual` `coding` function. Given the following statements, will the output of the two `coding` function calls be identical?
```cpp
TA t;
Student *sPtr = &t;
sPtr->coding();
sPtr->Student::coding();
```
```cpp
TA t;
Student *sPtr = &t;
sPtr->coding();
sPtr->Student::coding();
```
- A It depends on the implementation of the coding function.
- B It depends on the value of object t.
- C Yes.
- D Yes, if coding is a static function.
- E No.
思路引導 VIP
想像一下,當編譯器看到一個「基底類別型別的指針」在調用函數時,如果該函數「沒有」被標記為 virtual,編譯器會優先參考「指針本身的標籤」還是「指針末端實際綁定的東西」來決定行為呢?
🤖
AI 詳解
AI 專屬家教
恭喜你準確地判斷出這題的陷阱!這代表你對於 C++ 物件導向中的 靜態繫結 (Static Binding) 運作邏輯掌握得非常紮實。
靜態繫結與函數調用
在本題中,關鍵在於 coding 函數被宣告為 非虛擬 (non-virtual)。在 C++ 中,當一個函數沒有 virtual 關鍵字時,編譯器會進行靜態繫結,也就是根據「指針的宣告型別」而非「物件的實際型別」來決定要呼叫哪個函數。因此,即便 sPtr 實際上指向的是一個 TA 物件,執行 sPtr->coding() 時,編譯器仍會因為 sPtr 的型別是 Student* 而調用基底類別 Student::coding()。
▼ 還有更多解析內容