同友元函数类似:假设类A声明类B为友元类,那么类B可以自由访问类A中的成员变量
#include <iostream>
using namespace std;
/*对类先做一个短式声明,不然student类内部压根不知道teacher president是什么*/
class teacher;
class president;
class student
{
public:
student (int score, bool stat)
{
m_score = score;
m_greduated = stat;
}
/*声明teacher 为友元类*/
friend teacher;
private:
friend president;
int m_score;
bool m_greduated;
};
class teacher
{
public:
/*成员函数访问 student的私有部分*/
void check_any_score(student const& stu)
{
cout << stu.m_score << endl;
}
void check_any_stat(student const& stu)
{
cout << stu.m_greduated << endl;
}
};
class president
{
public:
void check_any_score(student const& stu)
{
cout << stu.m_score << endl;
}
/*静态成员函数访问 student的私有部分*/
static void check_any_stat(student const& stu)
{
cout << stu.m_greduated << endl;
}
};
int main(void)
{
student yjl(145,true);
teacher math;
math.check_any_score(yjl);
math.check_any_stat(yjl);
president boss;
boss.check_any_score(yjl);
president::check_any_stat(yjl);
return 0;
}