C++ protected访问标号

本文深入解析C++中protected成员的特点及使用限制,包括其对于派生类的访问规则,并通过实例代码展示了如何正确访问基类的protected成员。

刚看完C++Primer,过了几天,用到了protected,结果记得不是很清楚,在这做个备忘吧。

我再次读《C++ Primer》的时候,其中关于protected 成员的描述是这样的:

protected Members

The protected access label can be thought of as a blend of private and public :

  • Like private members, protected members are inaccessible to users of the class.
  • Like public members, the protected members are accessible to classes derived from this class.
  • In addition, protected has another important property:
    A derived object may access the protected members of its base class only through a derived
    object. The derived class has no special access to the protected members of base type objects.
第一条和第二条应该都容易理解,第三条稍微麻烦些。

关于第三条,我的理解是这样的:派生类在访问基类的protected的成员时,只有通过派生类的对象进行访问,而不能通过对基类的引用进行访问。

举一个简单的例子:

#include <iostream>
using namespace std;
class Base
{
public:
	Base(){};
	virtual ~Base(){};
protected:
	int int_pro;
};
class A : public Base
{
public:
	A(){};
	A(int da){int_pro = da;}
	void Print(A &obj){obj.int_pro = 24;}
	void PrintPro(){cout << "The proteted data is " << int_pro <<endl;}
};
int main()
{
	A aObj;
	A aObj2(5);
	aObj2.PrintPro();
	aObj.Print(aObj2);
	aObj2.PrintPro();
	
         //注释1
         //aObj.int_pro = 8;
}

编译运行结果如下:

The protected data is 5

The protected data is 24

可是如果去掉注释1,就会出现编译错误;

最后注明一点:派生类只能访问基类的public,而不能访问基类的private
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值