面向对象中的重载、覆盖和隐藏
1.重载是一个类内部实现相同机理的操作,但是操作的对象不同。主要体现在:
- 方法在同一个类中
- 重载的方法名称相同
- 参数不同(参数的类型不同,参数的个数不同)
- virtual关键字可有可无
#include "stdafx.h" #include<iostream> using namespace std; class father { public: void DoJob(int a); void DoJob(double a); void DoJob(int a, int b); void DoJob(int a, int b, int c); ~ father(); private: }; void father::DoJob(int a) { cout << "one parameter:" << a << endl; } void::father::DoJob(double a) { cout << "one double parameter:" << a << endl; } void father::DoJob(int a, int b) { cout << "two parameter: " << a << " and " << b << endl; } void father::DoJob(int a, int b, int c) { cout << "three parameter:" << a << " and " << b << " and " << c << endl; } father::~ father() { } int _tmain(int argc, _TCHAR* argv[]) { father f; f.DoJob(4); f.DoJob(4.3); f.DoJob(5, 6); f.DoJob(4, 5, 6); return 0; }father类的DoJob方法实现了重载,其中既有参数类型不同的重载,也有参数个数不同的重载。
2.覆盖,就是面向对象中的多态,是子类的方法覆盖了基类的方法,以实现不同的功能,或者对父类的功能进行扩充。主要体现在:
- 派生类函数覆盖基类函数
- 不同的范围(分别位于派生类和基类中)
- 函数名称相同
- 参数相同
- 基类函数必须有virtual关键字
#include "stdafx.h" #include<iostream> using namespace std; class father { public: virtual void DoJob(int a); ~ father(); private: }; void father::DoJob(int a) { cout << "one parameter in base class:" << a << endl; } father::~ father() { } class son :public father { public: void DoJob(int a); ~son(); }; void son::DoJob(int a) { cout << "one parameter in son class:" << a << endl; } son::~son() {} int _tmain(int argc, _TCHAR* argv[]) { son s; father *f = &s; f->DoJob(5); return 0; }
上述代码的运行结果为:
上面的代码中子类son中的函数DoJob()对父类father中的函数DoJob()进行了覆盖。
3.隐藏是派生类的函数屏蔽了与其同名的基类函数。其特点主要体现在:
- 如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无virtual关键字,基类的函数都将被覆盖。
- 如果派生类的函数与基类的函数同门,并且参数也相同,但是基类函数没有virtual关键字。此时,基类的函数也将被隐蔽。还记得吗如果此时基类函数如果有virtual,子类函数就覆盖了父类函数。
#include "stdafx.h" #include<iostream> using namespace std; class father { public: virtual void DoJob(int a); virtual void DoJob(int a, int b); ~ father(); private: }; void father::DoJob(int a) { cout << "one parameter in base class:" << a << endl; } void father::DoJob(int a, int b) { cout << "two parameter in base class:" << a << " and " << b << endl; } father::~ father() { } class son :public father { public: void DoJob(double a); ~son(); }; void son::DoJob(double a) { cout << "one parameter in son class:" << a << endl; } son::~son() {} int _tmain(int argc, _TCHAR* argv[]) { son s; s.DoJob(1); s.DoJob(2, 3); return 0; }
对上面的代码进行编译,会出现错误:
error C2660: “son::DoJob”: 函数不接受 2 个参数,这就说明基类father中的DoJob(int a,int b)函数被隐藏了。
最后更新:2017-04-03 12:54:03