写继承时,经常有人以为基类的友元能自动访问派生类,但 C++ 不是这么设计的。友元关系不能继承——'你父亲的朋友,不等同就是你的朋友'。
友元关系不可继承
如果想让某个函数同时访问基类和派生类的私有/保护成员,必须在两边都声明友元。看个典型错误:
#include <iostream>
#include <string>
using namespace std;
// 错误:Student 尚未定义,且友元不可继承
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; // 报错:无法访问
}
这段代码有两个编译错误。第一个是因为 friend 声明用到了 Student,但此时 Student 还不可见——前置声明能解决。第二个错误才是核心:基类的友元不能自动访问派生类的 _stuid,即使你是它的'子类'也不行。
正确做法:派生类里也加上友元声明,并前置声明 Student:
#include <iostream>
#include <string>
using namespace std;
class ;
{
:
;
:
string _name = ;
};
: Person {
;
:
_stuid = ;
};
{
cout << p._name << endl;
cout << s._stuid << endl;
}






