
前言
在 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);
}
{
();
;
}



