51 C++ 继承方式

这篇博客详细介绍了C++中的继承权限,包括公共继承、保护继承和私有继承。通过示例代码展示了不同继承方式下子类成员的访问特性,强调了访问控制在面向对象编程中的重要性。

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

 

 

#include"inherit_02.h"

class Base
{
public:
	int a;
protected:
	int b;
private:
	int c;
};

// 公共继承
class ChildrenA :public Base
{
	void writer()
	{
		a = 10;// 公共权限
		b = 10;// 保护权限
		//c = 10;// c是私有函数所以无法赋值
	}

};

//保护继承
class ChildrenB :protected Base
{
	void writer()
	{
		a = 10;// 保护权限可赋值
		b = 10;// 保护权限可赋值
		//c = 10;// c是私有函数所以无法赋值
	}
};

// 私有继承
class ChildrenC :private Base
{
	void writer()
	{
		a = 10;// 私有权限可赋值
		b = 10;// 私有权限可赋值
		//c = 10;// c是私有函数所以无法赋值
	}
};

void inherit_02_test_01()
{
	ChildrenA mai;
	cout << mai.a << endl;//可访问
	//cout << mai.b << endl;// 不可访问子类的保护权限成员
	//cout << mai.c << endl;// 不可访问子类的私有权限成员

	ChildrenB song;
	//cout << song.a << endl;//不可访问子类的保护权限成员
	//cout << song.b << endl;//不可访问子类的保护权限成员
	//cout << song.c << endl;//不可访问子类的私有权限成员

	ChildrenB lee;
	//cout << lee.a << endl;//不可访问子类的私有权限成员
	//cout << lee.b << endl;//不可访问子类的私有权限成员
	//cout << lee.c << endl;//不可访问子类的私有权限成员
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值