重载、覆盖、隐藏
1.概念
a)重载
1.相同范围(同一个类中)
2.函数名相同、参数类型不同或参数个数不同
3.virtual关键字可有可无
b)覆盖
1.不同范围(分别在基类和派生类)
2.函数名相同、参数相同
3.基类函数必须有virtual关键字
c)隐藏
1.不同范围(分别在基类和派生类)
2.如果派生类和基类函数名相同,参数不同,这时,不管基类函数有没有virtual关键字,基类函数都被隐藏
3.如果派生类和基类函数名相同,参数相同,没有virtual关键字,基类函数会被隐藏
2.例子
重载:
class Base
{
public:
void func(){}
void func(int a){}
};
覆盖:
class Base
{
public:
virtual void func(int a){}
};
class Derived : public Base
{
public:
void func(int a){}
};
隐藏:
class Base
{
public:
void func(){}
void func(int a){}
};
class Derived : public Base
{
public:
void func(int a){}
};
3.隐藏导致的陷阱
#include <iostream>
using namespace std;
class Base
{
public:
virtual void vf(float x) { cout << "Base::vf(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 vf(float x) { cout << "Derived::vf(float) " << x << endl; }
void g(int x) { cout << "Derived::g(int) " << x << endl; }
void h(float x) { cout << "Derived::h(float) " << x << endl; }
};
int main()
{
Derived d;
Base *pb = &d;
Derived *pd = &d;
// Good : behavior depends solely on type of the object
pb->vf(3.14); // Derived::vf(float) 3.14
pd->vf(3.14); // Derived::vf(float) 3.14
// Bad : behavior depends on type of the pointer
pb->g(3.14); // Base::g(float) 3.14
pd->g(3.14); // Derived::g(int) 3 (suprise!)
// Bad : behavior depends on type of the pointer
pb->h(3.14); // Base::h(float) 3.14 (suprise!)
pd->h(3.14); // Derived::h(float) 3.14
return 0;
}