C++学习之路,从0到精通的征途:继承-五.继承与友元

时间:2025-05-15 09:10:04

        友元关系不能继承,也就是说基类友元不能访问派生类私有和保护成员 。

class Student; // 前置声明

class Person
{
public:
	friend void Display(const Person& p, const Student& s);
protected:
	string _name; // 姓名
};

class Student : public Person
{
protected:
	int _stuNum; // 学号
};

void Display(const Person& p, const Student& s)
{
	cout << p._name << endl;
	cout << s._stuNum << endl; 
}

int main()
{
	Person p;
	Student s;
	// 编译报错:error C2248: “Student::_stuNum”: 无法访问 protected 成员
	// 解决方案:Display也变成Student 的友元即可
	Display(p, s);
	return 0;
}