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。
posted @ 2015-02-16 10:32  mengfanrong  阅读(203)  评论(0)    收藏  举报
众安尊享e升2025版 - 底部横幅广告
尊享e升 2025版
🚀 全新升级
百万医疗险全面升级 守护健康人生
✓ 一般医疗300万
✓ 重疾600万
✓ 6年保证续保
✓ 1万免赔额
600万
最高保障
首月特惠价
低至1元起
🛡️ 立即投保