直接上例子:
#include "stdafx.h"
#include
using namespace std;
class Base
{
public:
void f(int x){cout << "Base::f(int)" <<endl;}
void f(float x){cout << "Base::f(float)" <<endl;}
virtual void g(void){cout << "Base::g(void)" << endl;}
};
class Derived : public Base
{
public:
virtual void g(void){cout << "Derived::g(void)" << endl;}
};
int _tmain(int argc, _TCHAR* argv[])
{
Derived d;
Base *pb = &d;
Base b;
pb->f(42);
pb->f((float)4.2);
pb->g();
cout<<endl;
d.f(42);
d.f((float)4.2);
d.g();
cout<<endl;
b.g();
cout<<endl;
int n;
cin >> n;
return 0;
}
執行結果:
結論:
方法被重載後會根據參數的類型自動調用相應的方法
子類重寫了父類的抽象方法後,除非直接實例化父類,要不然後子類的方法會覆蓋父類的方法