• C++语言笔记系列之十二——C++的继承


    C++的继承

    1.继承方式


    public(公有继承)
    派生类中的成员能够訪问基类的public成员和protected成员,但不能訪问基类的private成员。
    派生类的对象仅仅能訪问基类的public成员。
    protected(保护继承),private(私有继承)
    派生类中的成员能够訪问基类的public成员和protected成员,但不能訪问基类的private成员。
    派生类的对象不能訪问基类的不论什么成员。
    2.样例
    example 1:

    #include <iostream.h>
    class A
    {
    public:
        void fun1(int a) {cout<<a<<endl;}
        void fun2(int b) {cout<<b<<endl;}
    };

    class B:public A
    {
    public:
        void fun3() {cout<<"It is in class B."<<endl;}
    };

    int main()
    {
        B b;
        A a;
        b.fun3(); //Y(正确)
        b.fun2(); //Y
        b.fun1(); //Y
        a.fun3(); //N(错误)
        a.fun2(); //Y
        a.fun1(); //Y
    }

    example2:

    #include <iostream.h>
    class A
    {
    public:
        void f1();
        A() {i1 = 10; j1 = 11;}
    protected:
        int j1;
    private:
        int i1;
    };
    class B:public A
    {
    public:
        void f2();
        B() {i2 = 20; j2 = 21;}
    protected:
        int j2;
    private:
        int i2;
    };
    class C:public B
    {
    public:
        void f3();
        C() {i3 = 30; j3 = 31;}
    protected:
        int j3;
    private:
        int i3;
    };
    下面说法:
    (1)派生类B中的成员f2()能够訪问类A中的成员f1()(Y)、i1(N)、j1(Y)。
    (2)派生类对象B可以訪问类A的成员f1()(Y)、i1(N)、j1(N)。
    (3)派生类C中的成员函数f3()是否能訪问直接基类B中的成员f2()(Y)、i2(N)、j2(Y);是否能訪问间接基类A中的f1()(Y)、i1(N)、j1(Y)。
    (4)派生类对象C可否訪问f2()(Y)、i2(N)、j2(N);可否訪问i1(N)、f1()(Y)、j1(N)。
    注:类能够直接訪问类中的private、protected以及public成员;类的对象仅仅能够直接訪问类中的public。
  • 相关阅读:
    SAP分析云及协同计划
    使用SSH命令行远程登录运行在CloudFoundry上的应用
    如何远程调试部署在CloudFoundry平台上的nodejs应用
    Apache httpclient的execute方法调试
    如何用Java代码在SAP Marketing Cloud里创建contact数据
    nodejs request module里的json参数的一个坑
    如何在调用Marketing Cloud contact创建API时增加对扩展字段的支持
    Efim and Strange Grade
    Vitya in the Countryside
    Anatoly and Cockroaches
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4293764.html
Copyright © 2020-2023  润新知