【Bug记录】友元函数不能访问私有成员?

项目场景:

【Bug记录】友元函数不能访问私有成员?_第1张图片
问题源码:

class Person
{
public:
    friend void Display(const Person& p, const Student& s);

protected:
    string _name = "1"; // 姓名
};

class Student : public Person
{
protected:
    string _s = "2";
};

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

void test81()
{
    Person p;
    Student s;

    Display(p, s);
}

对比源码:

class Person
{
public:
    friend void Display(const Person& p);

protected:
    string _name = "1"; // 姓名
};

class Student : public Person
{
protected:
    string _s = "2";
};

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

void test82()
{
    Person p;
    Student s;
    
    Display(p);
}

问题描述

两种代码,第一个会报错,第二个不会报错。

主要的奇怪的问题是什么,就是在第一个报错的代码中我也明确写了友元函数了呀!


原因分析:

这个地方VS编译器报错:说_name变量不可访问。

其实这个地方是编译器有点误导人了,其实应该是Student类友元函数声明的时候不认识,因为Student类在友元函数声明的后面。


解决方案:

把Student类提到Parent前面去即可。
【Bug记录】友元函数不能访问私有成员?_第2张图片

class Student;//类的声明
class Person
{
public:
	friend void Display(const Person& p, const Student& s);

protected:
	string _name = "1"; // 姓名
};

class Student : public Person
{
protected:
	string _s = "2";
};

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

void test81()
{
	Person p;
	Student s;

	Display(p, s);
}


EOF

你可能感兴趣的:(Bug,bug,CPP)