【C++】友元函数以及友元类

声明:本文章是在学习了【传智扫地僧】的C++视频后做的笔记。可收藏,可转载。

友元函数

1)友元函数的作用:
类很好的将成员函数以及成员变量进行封装,并且设置public、protected、private用于限制访问。
而友元函数用于破坏类的封装性,可以通过与类“交朋友,获得批准”,对传入全局函数中的对象的私有属性进行修改。用于操作符重载中的<<、>>。

2)实例:

#include <iostream>
using namespace std;

class A
{
public:
	A()
	{
		a1 = 100;
		a2 = 200;
	}
	int getA()
	{
		return this->a1;
	}
	friend void setA(A& obj, int a1); //将全局函数拷贝过来,并添加friend关键字即可,位置不限
protected:
private:
	int a1;
	int a2;
};

void setA(A& obj, int a1) //想访问对象的私有属性,因此需要传入对象引用
{
	obj.a1 = a1;
}

void main()
{
	A a;
	setA(a, 1);
	cout << a.getA() << endl; //output:1
	cout << "hello,world..." << endl;
	system("pause");
}

3)使用步骤:
定义全局函数;
输入参数中有对象的引用;
将函数在此类中进行声明,并添加关键字friend

友元类

1)作用:
友元类用于消息体或者封装的数据,通过一个类可以访问另一个类的私有函数以及私有变量。

2)实例:

#include <iostream>
using namespace std;

class A
{
public:
	A(int x)
	{
		this->x = x;
	}
	void printA()
	{
		cout << this->x << endl;
	}
	friend class B;//注意:声明友元类
protected:
private:
	int x;
};

class B
{
public:
	B(int y, int x):Aobject(x)//注意:传递初始化参数
	{
		this->m_y = y;
	}
	void setData(int x)
	{
		Aobject.x = x; //注意:调用友元类私有变量
	}
	void printB()
	{
		Aobject.printA(); //注意:调用友元类私有函数
	}
protected:
private:
	A Aobject; //B中包含有友元类对象
	int m_y;
};
void main()
{
	B b(1, 2);
	b.printB();
	cout << "hello,world..." << endl;
	system("pause");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值