C++面向对象入门(二十六)继承方式

基类不同访问权限的成员不同继承方式下访问权限

继承方式  基类成员  子类中访问权限  子类内存模块访问权限  子类对象访问性

私有继承  私有    不可访问的    不可访问        不可访问

      保护    保护的      可以访问        不可访问

      公有    公有的      可以访问        可以访问

保护继承  私有    不可访问的    不可访问        不可访问

      保护    私有成员     可以访问        不可访问

      公有    私有成员     可以访问        可以访问

公有继承  私有    不可访问的    不可访问        不可访问

      保护    保护的      可以访问        不可访问

      公有    保护的      可以访问        可以访问

 

 

代码示例:

#include <iostream>
using namespace std;

class A
{
private:
    int a;
protected:
    int b;
public:
    int c;
    A()
    {
        a = 1;
        b = 2;
        c = 3;
    }
};

class B :public A
{
public:
    void test();
    B():A(){}
};

class C :protected A
{
public:
    C() :A() {}
    void test();
};

class D :private A
{
public:
    D() :A() {}
    void test();
};

void B::test()
{
    //cout << "a :" << a << endl;
    //成员A::a不可访问
    cout << "b :" << b << endl;
    cout << "c :" << c << endl;
}

void C::test()
{
    //cout << "a : " << a << endl;
    //成员A::a不可访问
    cout << "b :" << b << endl;
    cout << "c :" << c << endl;
}

void D::test()
{
    //cout << "a : " << a << endl;
    //成员A::a不可访问
    cout << "b :" << b << endl;
    cout << "c :" << c << endl;
}

int main()
{
    B b;
    b.test();
    cout << b.c << endl;
    //公有继承A的派生类访问基类的公有成员
    C c;
    c.test();
    //公有继承A的派生类访问基类的公有成员
    //cout << c.c << endl;
    //成员A::a不可访问
    D d;
    d.test();
    //公有继承A的派生类访问基类的公有成员
    //cout << d.c << endl;
    //成员A::a不可访问
    system("pause");
    return 0;
}

 

posted @ 2020-08-31 20:05  DNoSay  阅读(100)  评论(0编辑  收藏  举报