C++友元

1. 友元定义

类的友元函数是定义在类内部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。 友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类,在这种情况下,整个类及其所有成员都是友元。如果要声明函数为一个类的友元,需要在类定义中该函数原型前使用关键字 friend

2.友元函数

友元函数也无法调用原类的成员,而是调用对象成员值

#include<iostream>
using  namespace std;
class Box
{
private:
	int Lenght{ 1 };
	int width{ 1 };
	int height{ 1 };
public:
	explicit Box(int x, int y, int z):Lenght  { x }, width  { y }, height { z }{} //三形参的构造函数
	int getLenght()  //函数调用私用成员
	{
		return Lenght;
	}
	int friend getwidth(Box box1) //友元函数调用私用成员
	{
		return box1.width;
	}
};
int main()
{
	Box box1{ 5,5,5 };  //显示调用
	cout << box1.getLenght() << endl;//调用函数
	cout << getwidth(box1) << endl; //待用友元函数
	return 0;
}

3. 友元类

友元类也无法调用原类的成员,而是调用对象成员值

#include<iostream>
using  namespace std;
class Box
{
private:
	int Lenght{ 1 };
	int width{ 1 };
	int height{ 1 };
public:
	explicit Box(int x, int y, int z):Lenght  { x }, width  { y }, height { z }{} //三形参的构造函数
	int getLenght()  //函数调用私用成员
	{
		return Lenght;
	}
	int friend getwidth(Box box1)
	{
		return box1.width;
	}
	friend class  bigBox;
};
class bigBox
{
public:
	int getheight(Box box1)
	{
		return box1.height;
	}
};

int main()
{
	Box box1{ 5,5,5 };  
	bigBox box2;
	cout << box1.getLenght() << endl;//结果5
	cout << getwidth(box1) << endl; //结果1
	cout << box2.getheight(box1) << endl;
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值