- 論壇徽章:
- 0
|
在C++ Primer 15.5.4中有一個例子,看了很久沒有看懂,請教一下大家(分割線中是書中的原話);
===============================================================
class Base {
public:
virtual int fcn();
};
class D1 : public Base {
public:
// hides fcn in the base; this fcn is not virtual
int fcn(int); // parameter list differs from fcn in Base
// D1 inherits definition of Base::fcn()
};
class D2 : public D1 {
public:
int fcn(int); // nonvirtual function hides D1::fcn(int)
int fcn(); // redefines virtual fcn from Base
};
從 Base 繼承的虛函數(shù)不能通過 D1 對象(或 D1 的引用或指針)調(diào)用,因為該函數(shù)被 fcn(int) 的定義屏蔽了。
通過基類類型的引用或指針調(diào)用函數(shù)時,編譯器將在基類中查找該函數(shù)而忽略派生類:
Base bobj; D1 d1obj; D2 d2obj;
Base *bp1 = &bobj, *bp2 = &d1obj, *bp3 = &d2obj;
bp1->fcn(); // ok: virtual call, will call Base::fcnat run time
bp2->fcn(); // ok: virtual call, will call Base::fcnat run time
bp3->fcn(); // ok: virtual call, will call D2::fcnat run time
===============================================================
對于bp1和bp3,都沒有問題,但是對于bp2 ,為什么是可以調(diào)用的,存在如下疑問:
1) bp2 實際指向的是D1 類型的對象,但是D1 類 中定義了fcn,屏蔽了Base中的fcn,為什么會調(diào)用Base中的fcn而不出錯?
2) 對于“通過基類類型的引用或指針調(diào)用函數(shù)時,編譯器將在基類中查找該函數(shù)而忽略派生類” 這句話,無法理解;對于虛函數(shù),不是應該動態(tài)綁定嗎?動態(tài)綁定的后果就是很有可能調(diào)用派生類中重新定義的虛函數(shù);為什么這里講“忽略派生類”? 如果忽略了派生類,如何實現(xiàn)動態(tài)綁定?
|
|