成员函数的重载&&隐藏&&覆盖

/*
*成员函数的重载,覆盖,隐藏
*重载:
*1.相同的范围(在同一个类中)
*2.函数名相同
*3.参数不同
*4.virtual关键字可有可无
*覆盖是指派生类覆盖基类的函数,特征是:
*1.不同的范围(分别位于基类与派生类中)
*2.函数名相同
*3.参数相同
*4.基类函数必须有virtual关键字
*/
#include<iostream>
using namespace std;
class B
{
public:
	 void f(int x)
	{cout<<"B::f(int)"<<endl;}
	void f(float x)
	{cout<<"B::f(float)"<<endl;}
	virtual void g(void)
	{cout<<"B::g(void)"<<endl;}	
};
class D : public B
{
public:
	virtual void g(void)
	{cout<<"D::g(void)"<<endl;}
};
int main()
{
	D d;
	B *pb = &d;
	pb->f(3.14f);//B::f(float)
	pb->f(42);//B::f(int)
	pb->g();//D::g(void)
	return 0;
}

/*
*隐藏:
*1.派生类的函数与基类函数同名,但参数不同。此时不论
*  有无virtual关键字基类函数将被隐藏
*2.派生类函数与基类函数同名同参,但基类没有virtual
*  关键字。基类函数将被隐藏
*/

#include<iostream>
using namespace std;
class B
{
public:
	virtual void f(float x)
	{cout<<"B::f(float)"<<endl;}
	void g(float x)
	{cout<<"B::g(float)"<<endl;}
	void h(float x)
	{cout<<"B::h(float)"<<endl;}	
};

class D : public B
{
public:
	virtual void f(float x)
	{cout<<"D::f(float)"<<endl;}
	void g(float x)
	{cout<<"D::g(float)"<<endl;}
	void h(float x)
	{cout<<"D::h(float)"<<endl;}
};

int main()
{
	D d;
	B *pb = &d;
	D *pd = &d;

	pb->f(3.14f);//D::f(float)//覆盖
	pd->f(3.14f);//D::f(float)

	pb->g(3.14f);//B::g(float)
	pd->g(3.14f);//D::g(float)//隐藏

	pb->h(3.14f);//B::h(float)
	pd->h(3.14f);//D::h(float)//隐藏
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值