How to access protected members in a derived class?

前端 未结 6 2010
说谎
说谎 2021-01-14 01:47

From http://www.parashift.com/c++-faq-lite/basics-of-inheritance.html#faq-19.5

A member (either data member or member function) declared in a protecte

6条回答
  •  别那么骄傲
    2021-01-14 02:19

    I think that the thing you are trying to do should looks like this:

    #include 
    using namespace std;
    
    class X
    {
        private:
            int var;
    protected:
        virtual void fun () 
        {
            var = 10;
            cout << "\nFrom X" << var; 
        }
    };
    
    class Y : public X
    {
    private:
        int var;
    public:
        virtual void fun () 
        {
            var = 20;
            cout << "\nFrom Y" << var;
        }
    
        void call ()
        {
            fun ();
    
    
            X::fun ();
        }
    };
    

    That way you can invoke hiden member from your base class. Otherwise you have to add friend X as it was pointed in other post.

提交回复
热议问题