类的私有继承与保护继承

类的保护成员与私有成员不能在类外访问。

class A
{
   protected:
   int  c;
};

int _tmain(_In_ int _Argc,char* _In_reads_)
{	
	A a;
	a.c=8;
	getchar();
	return 0;
}
```编译时不能通过   error C2248: “A::c”: 无法访问 protected 成员(在“A”类中声明)

public继承的情况

#include “stdafx.h”
class A
{
private:
int m_x;
int m_y;
public:
void SetX(int x)
{
m_x=x;
}

protected:
void SetY(int y)
{
m_y=y;
}
int c;
};

class B:public A
{
private:
public:
void set(int t)
{
SetY(t);
}
protected:

};

int _tmain(In int _Argc,char* In_reads)
{

B b;
b.SetX(10);
b.set(99);
getchar();
return 0;

}

public     结论: 派生类的对象不能访问基类的保护成员函数,  派生类可以设计一个接口(成员函数)访问基类的保护成员函数。

protected 继承的情况
#include "stdafx.h"
class A
{
private:
	int m_x;
	int m_y;
public:
	void   SetX(int x)
	{
		m_x=x;
	}
	
protected:
     void	SetY(int y)
	{
	  m_y=y;
	}
int c;
};

class B:protected A
{
private:
public:
	void set(int t)
	{
		SetY(t);
	}
protected:

};

int _tmain(_In_ int _Argc,char* _In_reads_)
{	
	
	B b;
	b.SetX(10);
	b.set(99);
	getchar();
	return 0;
}
编译报错  “A::SetX”不可访问,因为“B”使用“protected”从“A”继承
结论:保护继承的情况下,派生类的对象不能访问基类的公有成员函数。
 派生类可以设计一个接口(成员函数)访问基类的公有成员函数。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值