Home  >  Q&A  >  body text

c++ - 派生类的继承访问

class A
{
private:
    int age;
};
class B:private A
{
public:
 int Getage() 
 {
    return age;
 }
};
 B b1; 
 cout<< b1.Getage()<<endl; 派生类私有继承基类之后,基类中的所有成员相对于派生类都是私有的,派生类的成员函数无法访问基类中的私有成员,所以return age失败。

class A
{
protected:
 int age;
};
class B:private A
{
public:
 int Getage() 
 {
  return age;
 }
};
 B b1; 
 cout<< b1.Getage()<<endl; 将int age改成protected,继承方式还是private,为什么就可以访问了呢?私有继承基类之后,基类成员在派生类中不都是私有的吗?



阿神阿神2765 days ago744

reply all(4)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 12:00:01

    Private members cannot be inherited by subclasses and only belong to the class itself.
    Only protected and public members can be inherited by subclasses.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 12:00:01

    Try this

    cppclass A {
    public:
        int age;
    }
    
    class B: public A {
    }
    
    class C: private A {
    }
    
    B b;
    int ba = b.age;
    
    C c;
    int ca = c.age;
    

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 12:00:01

    Your understanding is wrong
    The subclass privately inherits the protected/public of the base class, and this member will become a private member of the subclass, which is equivalent to becoming

    class B:private A
    {
    private:
       int age;
    public:
     int Getage() 
     {
      return age;
     }
    };
    

    Of course you can access your own private members, so the usage of private inheritance is not only to prevent subclasses from inheriting their own private members (this is true for all types of inheritance), but also to make your own non-private members only Can be inherited once, preventing multiple levels of inheritance.

    Pay a form
    Inheritance method in base class In subclass

    public & public inheritance => public

    public & protected inheritance => protected

    public & private inheritance = > private

    protected & public inheritance => protected

    protected & protected inheritance => protected

    protected & private inheritance = > private

    private & public inheritance => subclasses have no access

    private & protected inheritance => subclasses have no access

    private & private inheritance = > subclasses have no access

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 12:00:01

    C++ primer fifth edition P543&&P544
    Derived access specifiers, that is, private inheritance, shared inheritance have no effect on members and friends of derived classes.
    The purpose of derived access specifiers is to control the access rights of derived class users to base class members. . Um, it's a bit abstract, isn't it? It's okay, you'll know after reading the book. . Haha

    reply
    0
  • Cancelreply