下列代碼之后的結果為(
adcee
)
#include<iostream> using namespace std; struct Base{ int i; virtual int f() { cout<<"a"; return 1; } virtual const Base &f() const { cout<<"b"; return *this; } int g() { cout<<"c"; return 3; } }; struct Derive:Base { int i; int f() { cout<<"d"; return 4; } const Base &f() const{ cout<<"e"; return *this; } int f(int=0) { cout<<"f"; return 6; } virtual int g() { cout<<"g"; return 7; } }; int main() { Derive d; const Derive d_const; Base b,*p=&d; const Base *p_const = &d_const; b.f(); p->f(); p->g(); p_const->f(); d_const.f(); }
1.b.f(); 基類對象直接調用基類的f()函數,輸出a
2.p->f(); 派生類對象賦給基類的指針,由於f()在基類中是虛函數,根據基類指針指向的對象進行調用,因此調用派生類的int f()輸出d
3.p->g();基類中g()不是虛函數,調用基類的g()
4.p_const->f();常對象,又由於基類中聲明為虛,同理用派生類中的函數
5.同理
只有在通過基類指針(或引用)間接指向派生類子類型時多態性才會起作用。派生類的指針只調用自己的函數!基類指針的函數調用如果有virtual則根據多態性調用派生類的函數,如果沒有virtual則是正常調用基類的函數。