0905C++友元

1.1 友元概述

  • 在程序里,有些私有属性 也想让类外特殊的一些函数或者类进行访问,就需 要用到友元的技术。
  • 友元的目的就是让一个函数或者类 访问另一个类中私有成员。
  • 相当于你的有些事情所有人都可以知道,但有些事情只能和你的朋友讨论。
    友元的关键字为 friend
    友元的三种实现:
  • 全局函数做友元
  • 类做友元
  • 成员函数做友元

1.2 全局函数做友元

#include<iostream>
#include<string>
using namespace std;
#include<string> 

class h{
	
 	friend void Mona(h* a);
 	public: 
 	string best_book = "薄荷双生" ;
 	private:
 	string best_idol = "道枝骏佑" ; 
 };
 
void Mona(h *a){
	cout << "我最喜欢的idol是:" << a->best_idol << endl;
	cout << "我最喜欢的书是:" << a->best_book << endl;
}
int main() {
     h H;
     Mona(&H);
	system("pause");
	return 0;
}
  • 告诉编译器 Mona全局函数 是 h类的好朋友,可以访问类中的私有内容
    输出:
我最喜欢的idol是:道枝骏佑
我最喜欢的书是:薄荷双生
请按任意键继续. . .

1.3 类做友元

//可以进行先声明类,再定义
class h00;
class h01{
	public: 
	h01();
	void visit_h00();
	private:
		h00 *h;		
 }; 
 class h00{
    friend class h01;
	public:
	h00(); 
 	string best_book;
 	private:
 	string best_idol; 	
};
//类外定义构造函数
h01::h01(){
	h = new h00;
}
//类外定义成员函数
void h01::visit_h00(){
	cout << "我最喜欢的idol是:" << h->best_idol << endl;
	cout << "我最喜欢的书是:" << h->best_book << endl;
}

h00::h00()
{
    best_book = "薄荷双生" ;
	best_idol = "道枝骏佑" ; 
}
//void Mona(h *a){
//	cout << "我最喜欢的idol是:" << a->best_idol << endl;
//	cout << "我最喜欢的书是:" << a->best_book << endl;
//}
int main() {
     h01 H;
     H.visit_h00();
	system("pause");
	return 0;
}

输出:

我最喜欢的idol是:道枝骏佑
我最喜欢的书是:薄荷双生
请按任意键继续. . .

1.4 成员函数做友元

class h00{
    friend void h01::visit_h00_0();
	public:
	h00(); 
 	string best_book;
 	private:
 	string best_idol; 	
};
void h01::visit_h00_0(){
	cout << "我最喜欢的idol是:" << h->best_idol << endl;
	cout << "我最喜欢的书是:" << h->best_book << endl;
}
	//没有再类内声明其为友元函数,故不可以访问私有成员 
void h01::visit_h00_1(){

//	cout << "我最喜欢的idol是:" << h->best_idol << endl;
	cout << "我最喜欢的书是:" << h->best_book << endl;
}

输出:

我最喜欢的idol是:道枝骏佑
我最喜欢的书是:薄荷双生
我最喜欢的书是:薄荷双生
请按任意键继续. . .
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值