小议 “重载”、“覆盖”、“隐藏”

重载--overload:同一作用域的函数,函数名相同,函数参数不同,在调用时可实现重载。同一个类的成员函数为一个作用域,继承来的函数与成员函数不在同一个作用域中。

#include<iostream>
using namespace std;
class base
{
	public:
		void f()
		{
			cout<<"void::f(void)"<<endl;
		}
		void f(int x)
		{
			cout<<"void::f(int)"<<endl;
		}
};
int main()
{
	base b;
	b.f();
	b.f(2);
	return 0;
}
如何使用继承来的函数进行重载--将函数名引入作用域
#include<iostream>
using namespace std;
class base
{
	public:
		void f()
		{
			cout<<"void::f(void)"<<endl;
		}
		void f(int x)
		{
			cout<<"void::f(int)"<<endl;
		}
};
class derived: public base
{
	public:
		using base::f;
		void f(double x)
		{
			cout<<"void::f(double)"<<endl;
		}
};
int main()
{
	derived b;
	b.f();
	b.f(2);
	b.f(3.0);
	return 0;
}


覆盖--override:因继承产生而产生的结果,子类和基类完全相同的函数(函数名,函数返回值,函数参数),基类的函数通过virtual修饰,在通过“指向子类对象的父类指针”调用时可实现多态。

#include<iostream>
using namespace std;
class base
{
	public:
		virtual	void f()
		{
			cout<<"base::f(void)"<<endl;
		}
		void f(int x)
		{
			cout<<"void::f(int)"<<endl;
		}
};
class derived: public base
{
	public:
		void f()//virtual可有可无
		{
			cout<<"derived::f(void)"<<endl;
		}
};
int main()
{
	derived b;
	base* p =&b;
	p->f();//调用子类的f();
	return 0;
}


隐藏--hide:因继承而产生的结果,子类和父类拥有相同的函数名,由于作用域的限制,导致子类的指针或对象无法调父类的同名函数。

借用重载的第二段代码,去掉using base::f;

#include<iostream>
using namespace std;
class base
{
	public:
		void f()
		{
			cout<<"void::f(void)"<<endl;
		}
		void f(int x)
		{
			cout<<"void::f(int)"<<endl;
		}
};
class derived: public base
{
	public:
		void f(double x)
		{
			cout<<"void::f(double)"<<endl;
		}
};
int main()
{
	derived b;
	b.f();//error
	b.f(2);//int转换为double调用derived::f();
	b.f(3.0);
	return 0;
}

这就是继承后,由于同名而产生的覆盖。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值