Toriyung

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

C++:private继承

平时我们使用类继承是这个画风:
class child:public::father
{};

表示子类child继承父类father,这里有个关键词"public",表示继承到的父类属性和方法为自己的public成员,这种情况下

子类的对象或者说实例化是可以直接访问这些成员的

 

当改成

class child:private::father
{};

则继承父类为自己的private成员,这种情况下

子类的对象是不可以直接访问的,只能通过类内成员访问

 

下面给个例子

复制代码
class A
{
private:
public:
 A(/* args */){};
 void APrint()
 {
    cout<<"i am A"<<endl;
 }
};

class B:private::A
{
private:
public:
 B(/* args */){};
 void callAPrint()
 {
    APrint();
 }
};

 int main()
 {
    A a;
    B b;

    cout<<"a.APrint()"<<endl;
    a.APrint();
    cout<<"b.APrint()"<<endl;
    b.APrint();
    cout<<"b.callAPrint()"<<endl;
    b.callAPrint();
    
    return -1;

 }
复制代码

B类以private的方式继承了A类。

然后我们实例化了A a,B b,并进行三个动作

父类A的对象a调用自己的方法APrint(), 是合法的

子类B的对象b调用从父类以private方式继承过来的方法APrint(),是不合法的

字类B的对象b调用其自己的方法,该方法在类内调用继承过来的方法APrint(),是合法的

 

实验结果

 可以看到第二种直接报错

 

我们屏蔽了第二种

 

 没问题

posted on   Toriyung  阅读(124)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示