C++——继承(1) 隐藏

本文详细解析了C++中的继承机制与访问控制概念,包括public、protected和private的使用,以及如何处理成员函数和变量的访问。同时,介绍了继承中的重载与隐藏现象,并通过具体代码示例进行说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 课前补充:
    C++ 中放在public中的成员可以直接访问,如person中的y在main函数中可以直接访问
    放在protected中不可以直接访问, 如cout << person.x << endl;//访问失败
    但可以通过成员函数进行访问,如person.eat();

继承中不能进行重载,如:父类中的函数有参,子类同名函数无参,子类不能直接调用父类的函数,否则会编译出错,通过子类.父类::函数(参数)来调用父类的有参函数。

class Person
{
	public:
		Person();
		~Person();
		void eat(){
			cout  << x << endl;
		}
		int y;
	protected:
		int x;
};

#include <iostream>

using namespace std;

int main(int argc, char** argv) {
	Person person;
	cout << person.y  << endl;
	person.eat();
	//cout << person.x << endl;//访问失败
	return 0;
}

隐藏

继承中的隐藏关键字:
在这里插入图片描述
隐藏:子类继承父类后,子类中有与父类同名的函数以及变量,则父类的函数及变量就会被隐藏,首先调用的是子类的函数或变量。
子类名.父类名::函数();调用被隐藏的函数或变量,
cooler.Man::play(); cout << cooler.Man::age << endl;

头文件


#include <iostream>
#include "Cooler.h"
#include "Man.h"

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
	Cooler cooler;
	cooler.play();
	
	cooler.Man::play();
	//cout << cooler.Man::age << endl;
	return 0;
}
class Man
{
	public:
		Man();
		void play();
		int age;
	protected:

};

cpp文件:
Man :: Man(){
	age = 20;
}

void Man :: play(){
	age = 20;
	cout << "Man-play()" << endl;
}
class Cooler : public Man
{
	public:
		void play();
		int age;
	protected:

};

cpp文件:
void Cooler :: play(){
	age = 10;
	cout << "Coolerplay()" << endl;
	cout << age << endl;
	cout << Man :: age << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

玖玖玖_violet

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值