include <iostream>
using namespace std;
class Base
{
public:
virtual void Show()
{
cout << "Base::Show()" << endl;
}
};
class Derive : public Base
{
public:
virtual void Show()
{
cout << "Derive::Show()" << endl;
}
};
void fun1(Base *ptr)
{
ptr->Show();
}
void fun2(Base &ref)
{
ref.Show();
}
void fun3(Base b)
{
b.Show();
}
int main()
{
Base b, *p = new Derive;
Derive d;
fun1(p);
fun2(b);
fun3(d);
system("pause");
return 0;
}
show()是虛函數;
*p是D對象,因此fun1(p)--》Derive;
b是B對象,因此fun2(b) --》Base;
d是D對象,B是D的父類,調用fun3(d)會將d轉成B對象,因此,輸出Base;
Derive::Show()
Base::Show()
Base::Show()