直接上例子:
#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;
}
执行结果:
![C++ <wbr>类的多态(方法的重载与继承) C++ <wbr>类的多态(方法的重载与继承)](https://i-blog.csdnimg.cn/blog_migrate/711a1828a115e9c3f32f0ae249676627.jpeg)
结论:
方法被重载后会根据参数的类型自动调用相应的方法
子类重写了父类的抽象方法后,除非直接实例化父类,要不然后子类的方法会覆盖父类的方法