How to make a derived class access the private member data?

前端 未结 5 953
忘掉有多难
忘掉有多难 2021-02-06 03:42

I\'m stuck with a c++ problem. I have a base class that has a self referential object pointer inside the private visibility region of the class. I have a constructor in the base

5条回答
  •  Happy的楠姐
    2021-02-06 04:11

    There is no other way to access other class's private data then friendship. What you can do with inheritance, however, is to access protected data of the base class. But it doesn't mean you can access protected data of another object of the base type. You can only access protected data of the base part of the derived class:

    class base{
    protected:  //protected instead of private
         base *ptr1;
         int data;
    public:
         base(){}
         base(int d) { data=d; }
    };
    
    class derived:private base{
    public:
         void member();
    };
    
    void derived::member()
    {
        base *temp=new base(3); 
        //temp->ptr1 = 0; //you need friendship to access ptr1 in temp
    
        this->ptr1 = 0; // but you can access base::ptr1 while it is protected
    }
    
    int main(){}
    

提交回复
热议问题