C++友元

目录

简介

友元的三种实现

1.全局函数做友元

2.类做友元

3.成员函数做友元


简介

  在程序里有些私有属性,想让类外特殊的一些函数或者类进行访问可以采用友元技术。友元的目的就是让一个函数或者类访问另一个类的私有成员

友元的三种实现

1.全局函数做友元

#include<iostream> 
using namespace std; 
class Home {
	friend void visit(Home* home);
public:
	Home() {
		this->sittingroom = "客厅";
		this->bedroom = "卧室";
	}
	string sittingroom;
private:
	string bedroom;
};
void visit(Home* home) {
	cout << "访问" << home->bedroom << endl;
	cout << "访问" << home->sittingroom << endl;
}
int main() 
{  
	Home home;
	visit(&home);
	return 0; 
}

2.类做友元

#include<iostream> 
using namespace std; 
class goodfriend;
class Home {
	friend goodfriend;
public:
	Home() {
		this->sittingroom = "客厅";
		this->bedroom = "卧室";
	}
	string sittingroom;
private:
	string bedroom;
};
class goodfriend {
public:
	goodfriend() {
		home = new Home();
	}
	void visit() {
		cout << "访问" << home->bedroom << endl;
		cout << "访问" << home->sittingroom << endl;
	}
private:Home* home;
};
int main() 
{  
	goodfriend gf;
	gf.visit();
	return 0; 
}

3.成员函数做友元

#include<iostream> 
using namespace std; 
class Home;
class goodfriend {
public:
	goodfriend();
	void visit();
private:Home* home;
};
class Home {
	friend void goodfriend::visit();
public:
	Home() {
		this->sittingroom = "客厅";
		this->bedroom = "卧室";
	}
	string sittingroom;
private:
	string bedroom;
};
goodfriend::goodfriend() {
	home = new Home();
}
void goodfriend::visit() {
	cout << "访问" << home->bedroom << endl;
	cout << "访问" << home->sittingroom << endl;
}
int main() 
{  
	goodfriend gf;
	gf.visit();
	return 0; 
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值