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


被折叠的 条评论
为什么被折叠?



