c++基础(十三)——全局函数做友元

一、友元

友元可以让一些私有属性被类外特殊的一些函数或者类进行访问,换句话说,友元的目的就是让一个函数或者类访问另一个类中私有成员。
友元的关键字为:friend

二、友元的三种实现

1、全局函数做友元
案例如下:

class person
{
public:
	person()
	{
		m_boy = "18";
		m_girl = "18";

	}
public:
	string m_boy;

private:

	string m_girl;
};

void goodGay(person *p1)
{

	cout << "好基友正在访问:" << p1->m_boy << endl;
	cout << "好基友正在访问:" << p1->m_girl << endl;

}

此时cout << “好基友正在访问:” << p1->m_girl << endl;这一行会报错
错误 C2248 “person::m_girl”: 无法访问 private 成员(在“person”类中声明)
就是因为m_girl这一属性为私有,不能在全局变量中被访问到,这时候只需要将全局函数放到类中:

class person
{

	friend void goodGay(person *p1);

public:
	person()
	{
		m_boy = "18";
		m_girl = "18";
	}
public:
	string m_boy;
private:
	string m_girl;
};

此时就不会报错。

2、类做友元
案例如下:

class person1;
class  GoodGay
{
public:
	GoodGay();
public:
	void questions();
	person1 * p1;
};

class person1
{
	//GoodGay是本类中的好朋友,可以知道年龄
	friend class  GoodGay;
public:
	person1();

public:
	int m_boy;

private:
	int m_girl;
};

//类外写成员函数
person1::person1()
{
	m_boy = 18;
	m_girl = 18;
}

GoodGay::GoodGay()
{
	p1 = new person1;
}

void GoodGay::questions()
{
	cout << "好基友正在访问:" << p1->m_boy << endl;
	cout << "好基友正在访问:" << p1->m_girl << endl;
}

void test11()
{
	GoodGay g1;
	g1.questions();
}

3、成员函数做友元
案例如下:

class person1;
class  GoodGay
{
public:
	GoodGay();
	void questions();//可以访问私有成员
	void questions2();//不可以访问私有成员
	person1 * p1;

private:

};

class person1
{
	//GoodGay是本类中的好朋友,可以知道年龄
	friend void GoodGay::questions();
public:
	person1();

public:
	int m_boy;

private:
	int m_girl;

};

//类外写成员函数
person1::person1()
{
	m_boy = 18;
	m_girl = 18;
}

GoodGay::GoodGay()
{
	p1 = new person1;
}

void GoodGay::questions()
{
	cout << "好基友正在访问:" << p1->m_boy << endl;
	cout << "好基友正在访问:" << p1->m_girl << endl;

}

void GoodGay::questions2()
{
	cout << "好基友正在访问:" << p1->m_boy << endl;
	cout << "好基友正在访问:" << p1->m_girl << endl;

}

void test11()
{
	GoodGay g1;
	g1.questions();
	g1.questions2(); 

}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值