子类隐藏父类的同名函数

10 篇文章 0 订阅

在C++中,子类是不能重载父类函数的,因为重载只发生在同一个类中。

所以在不考虑虚函数重写的情况下,子类中所有的同名函数(仅仅是与父类的函数名称相同),都会导致父类的同名函数被隐藏

见代码:

#include <stdio.h>
#include <stdlib.h>

class CFather
{
public:
	void Test()
	{
		Print();
	}
	void Print()
	{
		printf("CFather\n");
	}
};

class CChild:public CFather
{
public:
	void Test()
	{
		Print();
	}
	void Print()
	{
		printf("CChild\n");
	}
};

int main()
{
	CChild child;
	child.Test();
	child.Print();
	system("pause");
}

在父类CFather和子类CChild中均实现了Test和Print方法,在main函数中声明了一个CChild类的对象,此时调用Test和Print方法,输出结果如下:

 以上的输出结果还是很好理解的,CChild类当然调用的是自己实现的方法。

那么以下的代码呢?

#include <stdio.h>
#include <stdlib.h>

class CFather
{
public:
	void Test()
	{
		Print();
	}
	void Print()
	{
		printf("CFather\n");
	}
};

class CChild:public CFather
{
public:
	void Print()
	{
		printf("CChild\n");
	}
};

int main()
{
	CChild child;
	child.Test();
	child.Print();
	system("pause");
}

CChild类中仅仅实现了Print这个同名函数,此时调用CChild从父类继承过来的Test方法,输出结果会怎么样呢?

 其实也很好理解,父类的Test方法内部调用的Print方法当然是父类自己的Print方法,因为是普通函数,不具有多态的特性

根据以上代码,可以总结归纳几点:
1、对于父类而言,子类的所有函数均不可见。
2、对于子类而言,父类中所有的同名函数都被隐藏了。
3、在父类的其他函数中访问同名函数,访问的均为父类的同名函数。
4、在子类的其他函数中访问同名函数,访问的均为子类的同名函数。

内容可能有些重复,但无伤大雅。

PS,顺带提一下,在子类中需要访问父类的同名函数时,一般用__super关键字来访问而不建议用父类的名称,因为会给人一种调用静态方法的感觉,例子如下:


#include <stdio.h>
#include <stdlib.h>

class CFather
{
public:
	void Test()
	{
		Print();
	}
	void Print()
	{
		printf("CFather\n");
	}
};

class CChild:public CFather
{
public:
	void Test()
	{
		Print();
	}
	void Print()
	{
		printf("CChild\n");
	}
	void FatherTest()
	{
        //CFather::Test();  //建议用__super::
		__super::Test();
	}
	void FatherPrint()
	{
        //CFather::Print();
		__super::Print();
	}
};

int main()
{
	CChild child;
	child.Test();
	child.Print();
	child.FatherTest();
	child.FatherPrint();
	system("pause");
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇龍_

若帮助到你,希望能给予鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值