C++学习笔记:函数的隐藏与覆盖

函数的隐藏:
1.派生类与基类的函数完全相同(函数名和参数列表都相同),只是基类的函数没有使用virtual关键字。此时基类的关键字将被隐藏,而不是覆盖。
2.派生类的函数与基类的函数同名,但参数列表不同,在这种情况下,不管基类的函数声明是否有virtual关键字,基类的函数都将被隐藏。(与重载区分)

继续使用这个学习例程,基类animal中定义了虚函数breathe(),派生类fish中定义了breathe(int a)函数。
1.一开始fn传入的还是指向animal类型的指针,若在fn中调用species->breathe();我们发现可以输出animal breathe。
species->breathe(1);animal::breathe不接受一个参数。
species->fish::breathe(1);提示限定名不是类“animal”或其基类的成员了。
2.fn传入指向fish的指针,
species->breathe(1);输出fish breathe。
species->animal::breathe();输出animal breathe。
//species->breathe();非法,提示fish::breathe函数不接受0个参数。


#include<iostream>
#include<stdlib.h>
#include<typeinfo.h>
using namespace std;
class animal
{
public:
	void eat()
	{
		cout<<"animal eat"<<endl;
	}
	void sleep()
	{
		cout<<"animal sleep"<<endl;
	}
	virtual void breathe()
	{
		cout<<"animal breathe"<<endl;
	}
};
class fish:public animal
{
public:
	void breathe(int a)
	{

		cout<<"fish breathe"<<endl;
	}
	void test()
	{
		cout<<"test"<<endl;
	}
};

void fn(fish* species)
{
	//species->fish::breathe();
	//species->fish::test();
	species->breathe(1);
	//species->breathe();
	species->animal::breathe();
	cout<<typeid(species).name()<<endl;
}
void main()
{
	fish fh;
	fish* fit;
	fit=&fh;
	fn(fit);
	//fn(fh);
	cout<<typeid(fit).name()<<endl;
	cout<<typeid(fh).name()<<endl;
	//cout<<typeid(fh).name()<<endl;
	system("pause");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值