C++,友元,语法+示例,非常详细!!!!

友元概念

友元的目的就是让一个函数或者类 访问另外一个类中的私有成员

友元的关键字为 friend

友元的几种实现

  • 全局函数做 友元
  • 类做 友元
  • 成员函数做 友元
  • 重载函数做 友元

全局函数做 友元

#include<iostream>
using namespace std;
class Building
{
	//Friend 全局函数 是 类 Building 的友元 ,可以访问私有属性 
	
	friend void Friend(Building *building);
	public:
		string SittingRoom;
		
		Building()
		{
			SittingRoom = "客厅";
			BedRoom = "卧室";
		}
	private:
		string BedRoom;
		
};
void Friend(Building *building)
{
	cout<<"朋友  "<<building->SittingRoom<<endl; 
	cout<<"朋友  "<<building->BedRoom<<endl; 
}
void test()
{
	Building building;
	Friend(&building);
} 
int main()
{
	test(); 
	return 0;	
} 

普通函数做 友元

即把一个 不属于任何类的普通函数作为某个类的友元函数

#include<iostream>
using namespace std;
class Date
{
	int year,month;
	public:
		Date(int y,int m)
		{
			year = y;
			month = m;
		}
		friend bool Equal(Date d1,Date d2);		
};
bool Equal(Date d1,Date d2)		//普通函数
{
	return (d1.year == d2.year && d1.month == d2.month);
}
int main()
{
	Date you(2020,1),my(2020,2);
	if(Equal(you,my))
		cout<<"1";
	else cout<<"0";
	return 0;
}

重载函数做友元

#include<iostream>
using namespace std;
class Complex
{
	private:
		double a,b;
	public:
		Complex():a(0.0),b(0.0){
		}
		Complex(double _a,double _b)
		{
			a = _a;
			b = _b; 
		}
		friend Complex operator-(Complex A,Complex B);
		void Print()
		{
			cout<<"("<<a<<","<<b<<")";
		}
};
Complex operator-(Complex A,Complex B)
{

	A.a -= B.a;
	A.b -= B.b;
	return A;
}
int main()
{
	Complex A(5.1,2.2);
	Complex B(3.3,2.5);
	A = B - A;
	A.Print();	
	return 0;
}

18

类做 友元

当类A把另一个类B声明为自己的friend之后,B中所有成员函数就都是A的友元函数,可以访问A中成员变量,(A中定义B是友元,B能调用A的成员变量)

举例

#include<iostream>
using namespace std;
class Person;   //因为Person是友元,在声明之前需定义 
class Date
{
	private:
		int year,month,day;
	public:
		Date(int y,int m,int d)
		{
			year = y;
			month = m;
			day = d;
		}
		void Disp()
		{
			cout<<"您需要的日期信息:"<<endl;
			cout<<year<<"-"<<month<<"-"<<day<<endl;
		}
		friend Person;		//Person  是  Date 的友元 ,在此处声明了,所以在前面要定义一下 
};
class Person
{
	private:
		string name;
	public:
		Person(string na)
		{
			name = na;
		}
		void Disp(Date d)		//传入 Date 的 对象 
		{
			d.Disp();			//调用Date的成员函数和数据成员 
			cout<<name<<"是";
			cout<<d.year<<"年出生的\n"; //此处调用了Date的private 数据
		}
};
int main()
{
	Person p("张三");
	Date birthday(2000,1,1);
	p.Disp(birthday);
	return 0;
}

10

说明

  1. 友元的关系是单向的。声明了类B是类A的友元,说明B能访问A的成员变量,但A不能访问B的 (题中Date类中设置了Person是友元,说明Person类可以调用Date类的private 数据,反之不能)
  2. 友元的关系不能传递。B是A的友元,C是B的友元,不代表C是A的友元。
  3. 友元的关系不能继承
  4. 实际工作中一般不会把整个类声明为友元类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值