012_linuxC++之_类的继承定义

(一)访问控制和继承
公有继承(public):当一个类派生自公有基类时,基类的公有成员也是派生类的公有成员,基类的保护成员也是派生类的保护成员,基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有和保护成员来访问。
保护继承(protected): 当一个类派生自保护基类时,基类的公有和保护成员将成为派生类的保护成员。
私有继承(private):当一个类派生自私有基类时,基类的公有和保护成员将成为派生类的私有成员。
访问权限总结出不同的访问类型,如下所示:
在这里插入图片描述
(二)使用示例

  1. 在同一个类中都可以使用
#include <iostream>
using namespace std;
class test{
public:
        int test1;
private:
        int test2;
protected:
        int test3;

        void A(void)
        {
            test1 = 0;
            test2 = 0;    /*error*/
            test3 = 0;
        }
};


int main(int argc, char **argv)

{

}
  1. 在派生类中不能访问private中的
#include <iostream>
using namespace std;
class test{
public:
        int test1;
private:
        int test2;
protected:
        int test3;

};

class Rectangle:public test{
public:
        void A(void)
        {
            test1 = 0;
        //    test2 = 0;    /*error*/
            test3 = 0;
        }

};
int main(int argc, char **argv)

{

}

运行结果,注销掉就能编译成功了
在这里插入图片描述

  1. 外部的类使用
#include <iostream>
using namespace std;
class test{
public:
        int test1;
private:
        int test2;
protected:
        int test3;
};


int main(int argc, char **argv)

{
    test S;
    S.test1 = 0;
    //S.test2 = 0;  /*error*/
    //S.test3 = 0;    /*error*/
}

运行结果,外部类无法使用protected和private,注销掉就成功了
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值