How to access protected members in a derived class?

前端 未结 6 2059
说谎
说谎 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:15

    See this example:

    #include 
    using namespace std;
    
    class X {
      private:
        int var;
      protected:
        void fun () 
        {
          var = 10;
          cout << "\nFrom X" << var; 
        }
    };
    
    class Y : public X {
      private:
        int var;
      public:
        void fun () 
        {
          var = 20;
          cout << "\nFrom Y" << var;
        }
    
        void call ()
        {
          fun(); /* call to Y::fun() */
          X::fun (); /* call to X::fun() */
    
          X objX;
          /* this will not compile, because fun is protected in X        
          objX.fun (); */
    
        }
    };
    
    int main(int argc, char ** argv)  {
      Y y;
      y.call();
      return 0;  
    }
    

    This yields

    From Y20
    From X10
    

    Because you have overloaded the fun()-method in Y, you have to give the compiler a hint which one you mean if you want to call the fun-method in X by calling X::fun().

提交回复
热议问题