重载的特征:
(1)相同的范围(在同一个类中)
(2)函数名相同
(3)参数不同
(4)virtual关键字可有可无
覆盖是指派生类函数覆盖基类函数,特征是:
(1)不同的范围(分别位于派生类与基类)
(2)函数名相同
(3)参数相同
(4)基类函数必须有vitrual关键字
隐藏的特征:
(1)不同的范围(分别位于派生类与基类)
(2)函数名相同
(3)参数可相同也可不同
(4)当参数相同时,基类函数没有被vitrual关键字修饰,形成隐藏关系
(5)当参数不同是,无论基类函数是否被vitrual关键字修饰,都形成隐藏关系
例:
class Base
{
public:
void f(int x){ cout<<"Base::f(int)"<<x<<endl; }
void f(float x) { cout<<"Base::f(float)"<<x<<endl; }
virtual void g(void){ cout<<"Base::g(void)"<<endl; }
};
class Derived:public Base
{
public:
virtual void g(void){ cout<<"Derived::g(void)"<<endl; }
};
函数Base::f(int)与Base::f(float) 相互重载
函数Base::g(void)被函数Derived::g(void) 覆盖(多态)
class Base
{
public:
virtual void f(float x) { cout<<"Base::f(float)"<<x<<endl; }
void g(float x) { cout<<"Base::g(float)"<<x<<endl; }
void h(float x) { cout<<"Base::h(float)"<<x<<endl; }
};
class Derived:public Base
{
public:
virtual void f(float x) { cout<<"Derived::f(float)"<<x<<endl; }
void g(int x) { cout<<"Derived::g(int)"<<x<<endl; }
void h(float x) { cout<<"Derived::h(float)"<<x<<endl; }
};
函数Derived::f(float) 覆盖了Base::f(float)
函数Derived::g(int) 隐藏了Base::g(float)
函数Derived::h(float x) 隐藏了Base::h(float x)