11.6.2重学C++之【继承方式】

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;



/*
    4.6.2 继承方式
        公共继承
        保护继承
        私有继承
*/



class Base{
public:
    int a;
protected:
    int b;
private:
    int c;
};



class Son1:public Base{
public:
    void func(){
        a = 10; // 父类中的公共权限成员,到子类中依然是公共权限
        b = 10; // 父类中的保护权限成员,到子类中依然是保护权限
        //c = 10; // 父类中的私有权限成员,子类不可访问
    }
};



class Son2:protected Base{
public:
    void func(){
        a = 10; // 父类中的公共权限成员,到子类中变为保护权限
        b = 10; // 父类中的保护权限成员,到子类中依然是保护权限
        //c = 10; // 父类中的私有权限成员,子类不可访问
    }
};



class Son3:private Base{
public:
    void func(){
        a = 10; // 父类中的公共权限成员,到子类中变为私有权限
        b = 10; // 父类中的保护权限成员,到子类中依然是私有权限
        //c = 10; // 父类中的私有权限成员,子类不可访问
    }
};



class GrandSon3:public Son3{
public:
    void func(){
        // 啥也访问不到
        //Son3是私有继承,所有继承Son3的属性在GrandSon3中都无法访问到
        //a = 10;
        //b = 10;
        //c = 10;
    }
};



void test1(){
    Son1 s1;
    s1.a = 100;
    //s1.b = 100; // 父类中b的为保护权限,传到子类son1中依然为保护权限,类外不可访问

    Son2 s2;
    //s2.a = 1000; // 父类中a的虽为公共权限,但传到子类son2中变为保护权限,类外不可访问

    Son3 s3;
    //s3.a = 2; // 私有继承时,从父类继承过来的公共、保护、私有,在子类中均为私有
}



int main()
{
    test1();

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HAIFEI666/article/details/114916842