雖然它沒有特別聲明,我假設TextWindow
派生(直接或間接)從Window
。
在這種情況下,基本問題是oops()
是否是虛擬成員函數。
如果oops()
是虛擬的,則通過指針或引用的呼叫基於動態類型 - 指針/引用實際引用的對象的類型。
如果oops()
不是虛擬的,然後通過一個指針或引用一個呼叫是基於靜態類型 - 指針被定義在點對象的類型,不管對象的類型的它實際上指着。
struct Window {
void oops() { std::cout << "Window::oops()\n"; }
virtual void oops2() { std::cout << "Window::oops2()\n"; }
};
struct TextWindow : Window {
void oops() { std::cout << "TextWindow::oops()\n"; }
virtual void oops2() { std::cout << "TextWindow::oops2()\n"; }
};
int main() {
Window w;
w.oops(); // Both of these print "Window::...".
w.oops2();
TextWindow tw;
tw.oops(); // Both of these print "TextWindow::...".
tw.oops2();
Window &w2 = tw;
w2.oops(); // oops() is not virtual, and we're using a reference to a Window,
// so this invokes Window::oops().
w2.oops2(); // oops2() is virtual, so even though w2 is a reference to a
// Window, this invokes TextWindow::oops2(), because the reference
// refers to the object tw, which is a TextWindow.
return 0;
}
這叫做多態性。 – twk 2011-06-09 15:27:31