C++ protected访问标号

来源:互联网 发布:照片查重软件 编辑:程序博客网 时间:2024/05/18 13:31

刚看完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
原创粉丝点击