public/protect/private和公有继承/保护继承/私有继承的简单理解

本文详细解析了C++中类成员的访问控制机制,包括public、protected和private的使用,以及在继承中的表现。通过实例代码展示了不同访问级别在类内外及继承中的具体效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、先来看一下没有继承的情况

类中的变量访问:

(1)类内访问方式:通过public成员函数访问

(2)类外访问方式:直接访问

表 1

class A
{
public:
    int  a;
protected:
    int  b;
private:
    int  c;
public:
    int getAll(){
        return a + b + c;
    }
};
int main()
{
    A testA;
    //类外访问方式
    testA.a;
    testA.b;
    testA.c;
    //类内访问方式
    testA.getAll();
    return 0;
}

其中标红的部分表示编译器会报错,你可以复制到IDE里试一下。

对照表1,类外访问是     可见/不可见/不可见,类内访问是 可见/可见/可见

 二、再来看一下有继承的情况

有继承的情况主要是对子类进行讨论,因为子类中的public/protect/private属性会发生变化。

表2

 

上表可以这么来记,private不可继承,公有继承不改变属性,保护继承属性全为protect,私有继承属性全为private。

class A
{
public:
    int  a;
protected:
    int  b;
private:
    int  c;
public:
    int getAll(){
        return a + b + c;
    }
};
//公有继承
class B :public A
{
public:
    int getA(){
        return a;
    }
    int getB(){
        return b;
    }
    int getC(){
        return c;
    }
};
//保护继承
class C :protected A
{
public:
    int getA(){
        return a;
    }
    int getB(){
        return b;
    }
    int getC(){
        return c;
    }
};
//私有继承
class D :private A
{
public:
    int getA(){
        return a;
    }
    int getB(){
        return b;
    }
    int getC(){
        return c;
    }
};

int main()
{
    B testB;
    C testC;
    D testD;

    //类外访问方式
//公有继承 testB.a; testB.b; testB.c; //保护继承 testC.a; testC.b; testC.c; //私有继承 testD.a; testD.b; testD.c; //类内访问方式
   //公有继承 testB.getA(); testB.getB(); testB.getC(); //保护继承 testC.getA(); testC.getB(); testC.getC(); //私有继承 testD.getA(); testD.getB(); testD.getC(); return 0; }

代码中标红的部分表示编译器会报错,我们逐个解释:

1、对照表2公有继承后,属性变为 public /protect/无;对照表1,类外访问是     可见/不可见/,类内访问是 可见/可见/

2、对照表2保护继承后,属性变为 protect/protect/无;对照表1,类外访问是 不可见/不可见/,类内访问是 可见/可见/

2、对照表2私有继承后,属性变为 private/private/无;对照表1,类外访问是 不可见/不可见/,类内访问是 可见/可见/

 

注意:以上全为博主自己琢磨的,没有参考过权威文献,仅供提供思路。

转载于:https://www.cnblogs.com/hustwx/p/9463969.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值