美文网首页
派生类的对象只能访问基类的public成员

派生类的对象只能访问基类的public成员

作者: Then丶 | 来源:发表于2020-06-02 17:09 被阅读0次
    • public(公有继承)
      派生类中的成员可以访问基类的public成员和protected成员,但不能访问基类的private成员。
      派生类的对象只能访问基类的public成员。
    • protected(保护继承),private(私有继承)

    派生类中的成员可以访问基类的public成员和protected成员,但不能访问基类的private成员。
    派生类的对象不能访问基类的任何成员。


    example 1:

      #include
    
      class A
    
      {
    
      public:
    
      void fun1(int a) {cout<
    
      void fun2(int b) {cout<
    
      };
    
      class B : public A
    
      {
    
        public:
    
          void fun3() {cout<<"It is in class B."<
    
      };
    
      int main()
    
      {
    
      B b;
    
      A a;
    
      b.fun3(); //Y(正确)
    
      b.fun2(); //Y
    
      b.fun1(); //Y
    
      a.fun3(); //N(错误)
    
      a.fun2(); //Y
    
      a.fun1(); //Y
    
      }
    

    example2:

      #include
    
      class A
    
      {
    
      public:
    
      void f1();
    
      A() {i1 = 10; j1 = 11;}
    
      protected:
    
      int j1;
    
      private:
    
      int i1;
    
      };
    
      class B:public A
    
      {
    
      public:
    
      void f2();
    
      B() {i2 = 20; j2 = 21;}
    
      protected:
    
      int j2;
    
      private:
    
      int i2;
    
      };
    

    原文: https://blog.csdn.net/luozhichu0614/article/details/49854177

    相关文章

      网友评论

          本文标题:派生类的对象只能访问基类的public成员

          本文链接:https://www.haomeiwen.com/subject/sntpzhtx.html