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

前端 未结 5 868
忘掉有多难
忘掉有多难 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条回答
  •  有刺的猬
    2021-02-06 04:05

    Well I think, you were trying to achieve a result like this!! This does not report any compiler error or such. Good luck!!!

    class base{
    private:
         base *ptr1;
         int data;
    public:
         base(){}
         base(int d) { data=d; }
         base* getPtr();   //getter to get access to base pointer
         void setPtr(base* val); // setter to set value of the pointer variable
    };
    
    base* base::getPtr()
    {
        return ptr1;
    }
    
    void base::setPtr(base* val)
    {
        ptr1 = val;
    }
    
    class derived:private base{
    private:
        base* getPtr();
        void setPtr(base* val);
    public:
         void member();
    
    };
    
    base* derived::getPtr()
    {
        return base::getPtr(); //derived version just invokes the base class version
    
    }
    
    void derived::setPtr(base* val)
    {
        base::setPtr(val);     //derived version just invokes the base class version
    
    }
    void derived::member()
    {
        base *temp=new base(5); //put in a random number here instead of val
        temp -> setPtr(nullptr);
    }
    

提交回复
热议问题