C++ 继承入门 (下):友元、静态成员与菱形继承的底层逻辑
前言
在上次《C++ 继承入门 (上):从基础概念定义到默认成员函数,吃透类复用的核心逻辑》文章中我们对继承的基础类复用进行了讲解,但除此之外友元、静态成员、菱形继承这些特殊场景往往是学习'继承'的理解难点。本篇文章将逐一讲解这些场景的底层逻辑,帮你彻底掌握继承的'隐藏规则'。
一. 友元 —— 友元关系不可继承
C++ 中,基类的友元函数/类无法直接访问派生类的私有成员。这就像'你父亲的朋友,不等同就是你的朋友',友元关系不具有继承性。如果需要让友元访问派生类成员,必须在派生类中重新声明一下友元。
1、错误版本
#include <iostream>
#include <vector>
using namespace std;
// 友元——友元不能被继承
class Person {
public:
friend void Display(const Person& p, const Student& s);
protected:
string _name = "张三"; // 姓名
};
class Student : public Person {
protected:
int _stuid = 123; // 学号
};
void Display(const Person& p, const Student& s) {
cout << p._name << endl;
cout << s._stuid << endl;
}
void Test1() {
Person p;
Student s;
Display(p, s);
}
int {
();
;
}


