重载:同域不同参
1:相同的作用域
2:相同的函数名
3:不同的参数
覆盖:异域同参虚覆盖(便于记忆:抑郁同餐需覆盖,基类种中必须是虚函数)
1:函数在基类种必须为虚函数
2:不同的作用于域
3:相同的参数
作用:基类调用此函数时将调用派生类中的函数,派生类调用正常(必须给基类指针赋予派生类对象)
隐藏:异域同名但无需(便于记忆:抑郁不想同餐,你就得隐藏起来)
1:不同的作用域
2:相同的函数名
第一种:
3:相同的参数
4:基类为非函数(若无此项就为覆盖了)
第二种:
3:不同的参数(则无论是否为虚函数都为隐藏)
作用:调用的函数取决于对象或指针的类型(基类的函数就调用基类的函数,派生类的对象就调用派生类的函数)
总结:隐藏与覆盖的区别
把覆盖的条件记住,其他的情况都为隐藏
#include<iostream>
#include<complex>
using namespace std;
class Base
{
public :
virtual void f( int );
virtual void f( double);
virtual void g( int=10 );
};
void Bace:: f(int)
{
cout<<"Bace:f(int)"<<endl;
}
void Bace:: f(double)
{
cout<<"Bace:f(double)"<<endl;
}
void Bace:: g(int)
{
cout<< i <<endl;
}
class Derived:public Base
{
public :
void f( copplex <double> );
void g( int=10 );
};
void Derived::f( copplex <double> )
{
cout<<"Derived:f(int)"<<endl;
}
void Derived:: g(int)
{
cout<< Derived::g() <<i<<endl;
}
void main()
{
Bace b;
Derived d;
Bace * pb=new Derived ;
b.f(1.0);
d.f(1.0);
pb->f(1.0);
b.g();
d.g();
pb->g();
delete pb;
}
输出的结果:
Bace:f(1.0)
Derived:f(1.0)
Bace:f(1.0)//注意??因为重载解析之作用于静态类型(Bace),而不是动态类型(Derived)
10
Derived::g() 20
Derived::g() 10//注意??//默认参数来自于对象的静态类型(Bace)
静态类型就是用于声明指针的类型,动态类型就是指针所指向的实际类型