C++|不同继承方式影响子类或外部函数的访问方式

如果有一个Derived类继承Base类时,有三种继承方式:public、protected、private。不同的继承方式会影响不同代码使用主体的访问方式:

不管哪种继承方式,不影响自身(Derived类)的访问属性。影响的是Derived做为基类时,其它继承Derived的子类及非友元的外部函数对Base类的访问属性:

1 public继承:

#include <stdio.h>
class Base
{
public:     int a;
protected:  int b;
private:    int c;
public:
};
class Derived:public Base
{
public:     int d;
protected:  int e;
private:    int f;
    void test()
    {
        //int t = c;
    }
};
class Layer3:public Derived
{
    void test()
    {
        //int t = c;
        //int u = f;
    }
};
void outsideFunc()
{
    Base b;
    //int t = b.b;
    //int u = b.c;
    Derived d;
    //int v = d.e;
    //int w = d.f;
    Layer3 l;
}
main()
{
    getchar();
}

不同继承方式影响其子类和外部函数的访问控制:

2 protected继承:

#include <stdio.h>
class Base
{
public:     int a;
protected:  int b;
private:    int c;
public:
};
class Derived:protected Base // protected inheritance
{
public:     int d;
protected:  int e;
private:    int f;
    void test()
    {
        //int t = c;
    }
};
class Layer3:public Derived
{
    void test()
    {
        //int t = c;
        //int u = f;
    }
};
void outsideFunc(Derived d)
{
    Base b;
    //int t = b.b;
    //int u = b.c;

    //int v = d.e;
    //int w = d.f;
    //int x = d.a; // …………
    //int y = d.d; // …………
    Layer3 l;
}
main()
{
    getchar();
}

3 private继承

#include <stdio.h>
class Base
{
public:     int a;
protected:  int b;
private:    int c;
public:
};
class Derived:private Base // pivate inheritence
{
public:     int d;
protected:  int e;
private:    int f;
    void test()
    {
        int u = a;
        int v = b;
        //int t = c;
    }
};
class Layer3:public Derived
{
    void test()
    {
        //int t = c;
        //int u = f;
        //int v = a; // …………
        //int w = b; // …………
    }
};
void outsideFunc(Derived d)
{
    Base b;
    //int t = b.b;
    //int u = b.c;
    Derived d;
    //int v = d.e;
    //int w = d.f;
    //int x = d.a;
    //int y = d.d;
    Layer3 l;
}
main()
{
    getchar();
}

我们知道,栈、队列是一种操作受限的线性表,是一种线性容器的适配器。如果有已经定义了一种类似vector的动态数组类(包括头部、尾部插入、删除、访问),怎样以这个动态数组类来定义栈或队列呢?答案是私有继承,让动态数组类的全部成员变为私有属性,不能被外部访问,而栈和队列需要的操作则在栈或队列的类中实现为public,且只需调用基类(也就是动态数组类)需要的操作即可(也就是不需要另外实现,在派生类中调用基类成员函数来实现需要的功能)。相关实现可以参考:C++|私有继承或组合链表类实现操作受限(接口适配)的栈和队列

ref:

https://www.learncpp.com/cpp-tutorial/inheritance-and-access-specifiers/

-End-

举报
评论 0