版权声明:本文为博主原创文章,但是欢迎转载! https://blog.csdn.net/yancola/article/details/82708215
重载
在同一作用域中函数名相同但参数不同(包括参数类型不同,参数个数不同或二者都不同)的函数称为重载(Overload)函数。
void print(const char *ch);
void print(int a);
void print(int a, int b);
print("Hello world");//调用print(const char *ch)
print(1);//调用print(int a);
print(13,32);//调用void print(int a, int b);
注意:main函数不能重载;函数是否重载与返回类型无关
覆盖
派生类中的成员函数与基类中的visual成员函数同名同参数,则派生类中的函数覆盖了基类中的成员函数。
#include <iostream>
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;}
};
int main()
{
Derived d;
Base *pb = &d;
pb->f(42); // Base::f(int)42
pb->f(3.14f); // Base::f(float) 3.14
pb->g(); // Derived::g(void)
return 0;
}
重载 | 覆盖 |
作用域相同,在同一类中 | 作用域不同,在基类和派生类之间 |
跟是否是虚函数无关 | 基类函数必须是visual |
参数不同 | 参数相同 |
隐藏
“隐藏”是指派生类的函数屏蔽了与其同名的基类函数,规则如下:
- 如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无 virtual关键字,基类的函数将被隐藏;
- 如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有 virtual关键字。此时,基类的函数被隐藏。
在下面的实例中:
- 函数 Derived::f(float)覆盖了 Base::f(float)。
- 函数 Derived::g(int)隐藏了 Base::g(float),而不是重载。
- 函数 Derived::h(float)隐藏了 Base::h(float),而不是覆盖。
#include <iostream> 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; } };