c++ - 派生类的继承访问
阿神
阿神 2017-04-17 11:58:01
0
4
740
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,为什么就可以访问了呢?私有继承基类之后,基类成员在派生类中不都是私有的吗?



阿神
阿神

闭关修行中......

reply all(4)
左手右手慢动作

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

Peter_Zhu

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;
伊谢尔伦

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

Peter_Zhu

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!