​C++ 的三级继承关系(爷爷 → 父亲 → 孙子)

在 ​C++ 的三级继承关系(爷爷 → 父亲 → 孙子)​​ 中,孙子类能否调用爷爷类的方法,​取决于继承方式和方法的访问权限。以下是详细分析:


1. 关键规则

  • 公有继承(public)​​:爷爷类的方法在孙子类中保持原有访问权限(public/protected 仍可访问)。

2. 三种继承方式对比

​(1)公有继承(推荐)​
class Grandfather {
public:
    void grandMethod() { cout << "爷爷的方法"; }
};

class Father : public Grandfather {  // 公有继承
    // grandMethod() 在 Father 中仍是 public
};

class Son : public Father {          // 公有继承
public:
    void callGrandMethod() {
        grandMethod();  // 可以调用爷爷的方法(通过父亲)
    }
};

结果​:
Son 可以直接调用 grandMethod(),因为继承链中权限未被削弱。


示例代码测试

复制
#include <iostream>
using namespace std;

class Grandfather {
public:
    void grandMethod() { cout << "爷爷的方法被调用\n"; }
};

class Father : public Grandfather {};  // 公有继承

class Son : public Father {
public:
    void test() {
        grandMethod();  // 成功调用
    }
};

int main() {
    Son s;
    s.test();       // 输出: "爷爷的方法被调用"
    s.grandMethod();// 也可直接调用(因为继承链中一直是 public)
    return 0;
}

输出​:

markdown

复制

爷爷的方法被调用
爷爷的方法被调用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值