Private/Protected继承

该博客探讨了C++中的类继承,包括public、protected和private继承的特性。通过实例展示了不同继承方式下,子类对父类成员的访问权限。重点在于理解public继承时的访问规则以及protected和private继承如何降低父类成员的访问级别。
摘要由CSDN通过智能技术生成
#include<iostream>
using namespace std;

class ClassA
{
public:
	int x;

	ClassA(int x = 1, int y = 2, int z = 3);
	~ClassA();

protected:
	int y;

private:
	int z;
};

class ClassB :protected ClassA
{
public:
	int a;
	void PublicShow();
	void OtherShow();

	ClassB(int a = 3, int b = 4, int c = 5, int x = 1, int y = 2, int z = 3);
	~ClassB();

protected:
	int b;
	void ProtectedShow();

private:
	int c;
	void PrivateShow();
};

int main()
{
	ClassB number(4, 5, 6, 1, 2, 3);
	number.OtherShow();
	return 0;
}

/*********A:构造************************************************/
ClassA::ClassA(int x, int y, int z)
{
	this->x = x;
	this->y = y;
	this->z = z;
}

ClassA::~ClassA()
{
}

/*********B:构造************************************************/
ClassB::ClassB(int a, int b, int c, int x, int y, int z) :ClassA(x, y, z)
{
	this->a = a;
	this->b = b;
	this->c = c;
}

ClassB::~ClassB()
{
}

/*********B:实现************************************************/
void ClassB::PublicShow()
{
	cout << x << "+" << y << "+" << a << "+" << b << "+" << c << endl;
}

void ClassB::ProtectedShow()
{
	cout << x << "+" << y << "+" << a << "+" << b << "+" << c << endl;
}

void ClassB::PrivateShow()
{
	cout << x << "+" << y << "+" << a << "+" << b << "+" << c << endl;
}
void ClassB::OtherShow()
{
	ProtectedShow();
	PrivateShow();
}
/*Public继承总结
* 1.ClassB无权限操作ClassA的private属性和方法
* 2.ClassB可以公开调用ClassA的public属性和方法,ClassA的protected,仅限在ClassB的内部交流用
* 3.public方法中,如果子类和父类方法相同,优先调用子类自己的方法,PublicShow()
*/
/*protected继承总结
* 1.ClassB无权限操作ClassA的private属性和方法
* 2.ClassA中的public和protected的属性和方法在ClassB中权限降为ClassB中protected
*/
/*private继承总结
* 1.ClassB无权限操作ClassA的private属性和方法
* 2.ClassA中的public和protected的属性和方法在ClassB中权限降为ClassB中private
*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值