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,为什么就可以访问了呢?私有继承基类之后,基类成员在派生类中不都是私有的吗?
Private members cannot be inherited by subclasses and only belong to the class itself.
Only protected and public members can be inherited by subclasses.
Try this
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
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
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