【友元函数】

友元函数的三种情况

1)全局函数做友元

2)类做友元

3)成员函数做友元

 

 

1)全局函数做友元

#include<iostream>
using namespace std;

class A{
	private:
		int n1;
	public:
		
};

void fun1(A* a){
	cout<<a->n1<<endl;    //错误   私有成员无法类外访问 
} 

int main(){
	return 0;
} 
#include<iostream>
using namespace std;

class A{
	private:
		int n1;
	public:
		friend void fun1(A* a);    //fun1成了A的友元函数,可访问私有成员
};

void fun1(A* a){
	cout<<a->n1<<endl;  
} 

int main(){
	return 0;
} 

2)类做友元

#include<iostream>
using namespace std;

class A{
	private:
		int n1;
};

class B{
	private:
		int n1;
	public:
		void show(A* a){
			cout<<a->n1<<endl;     //报错    无法访问A类的私有成员 
		}
};

int main(){
	return 0;
} 
#include<iostream>
using namespace std;

class A{
	
	friend class B;      // B类成了A类的友元类 

	private:
		int n1;
};

class B{
	private:
		int n1;
	public:
		void show(A* a){
			cout<<a->n1<<endl;     //正确     
		}
};

int main(){
	return 0;
} 

3)成员函数做友元

#include<iostream>
using namespace std;

class A;
class B{
	public:
		B();
		A* a;
		void show();
};
class A{
	//声明 B的成员函数show()为A类的友元函数,可访问A自身的私有成员 
	friend void B::show();
	public:
		A(){
			n1 = 100;
		};
	public:
		int n1;
};

B::B(){
	a = new A;
}

void B::show(){
		cout<<a->n1<<endl;     // B的成员函数可以访问A的私有成员 n1  
}

int main(){
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值