<C/C++基础>重载、覆盖、隐藏

重载(overload)、覆盖(override)、隐藏(hide)的区别


一,基本规则:

1,覆盖的特征有:

1) 分别位于派生类与基类

2) 函数名字必须相同;

3) 参数必须相同;(即函数必须两完全一样)

4) 基类函数必须有virtual关键字。


2,隐藏的特征有:

隐藏是指派生类的函数屏蔽了与其同名的基类函数:

1) 分别位于派生类与基类

2) 函数名字必须相同;

3) 参数可能相同;(即函数可以一样也可以不一样,一样的时候基类必须有virtual关键字)

4) 基类的同名函数可能有virtual关键字。


或者可以这样说:

1) 如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无virtual关键字,基类的函数将被隐藏。
2) 如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有virtual关键字。此时,基类的函数被隐藏。


两者的区分:函数的覆盖发生在派生类和基类之间,两个函数必须完全一样,并且都是虚函数,那么不属于这种情况的就是隐藏了!


见下面经典参考程序:

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

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:
	//函数Derived::f(float)覆盖了Base::f(float)。
	virtual void f(float x){ cout << "Derived::f(float) " << x << endl; }
	//函数Derived::g(int)隐藏了Base::g(float),而不是重载(因为参数列表不一样,并且不是虚函数)
	void g(int x){ cout << "Derived::g(int) " << x << endl; }
	//函数Derived::h(float)隐藏了Base::h(float),而不是覆盖(因为不是虚函数,尽管一模一样)
	void h(float x){ cout << "Derived::h(float) " << x << endl; }
};

int main(void)
{
	Derived  d;
	Base *pb = &d;//基类指针指向子类对象
	Derived *pd = &d;
	// Good : behavior depends solely on type of the object
	//在第一种调用中,函数的行为取决于指针所指向的对象(子类对象)
	pb->f(3.14f); // Derived::f(float) 3.14
	pd->f(3.14f); // Derived::f(float) 3.14

	//下面两种调用的是隐藏函数,他实际调用函数时根据指针类型,而不再是对象类型
	// Bad : behavior depends on type of the pointer
	pb->g(3.14f); // Base::g(float) 3.14
	pd->g(3.14f); // Derived::g(int) 3        (surprise!)


	// Bad : behavior depends on type of the pointer
	pb->h(3.14f); // Base::h(float) 3.14      (surprise!)
	pd->h(3.14f); // Derived::h(float) 3.14
	getchar();
	return 0;
}


3,重载的特征有

1)在同一个类中
2)函数名字相同
3)参数不同
4)virtual 关键字可有可无

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

#include<iostream>
using namespace std;

class myclass
{
public:
	myclass(){};
	~myclass(){};
	
	void print(int i){cout << "print a integer :" << i << endl;}
	//重载print函数
	void print(string str){cout << "print a string :" << str << endl;}
private:

};

int main()
{
	myclass m;
	m.print(12);
	m.print("hello world!");
	getchar();
	return 0;
}





参考资源:

【1】孙鑫VC++深入详解

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值