在 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
复制
爷爷的方法被调用
爷爷的方法被调用
17万+

被折叠的 条评论
为什么被折叠?



