19~C++友元类

同友元函数类似:假设类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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值