c++友元

友元的目的就是让一个函数或者类访问另一个类中私有成员
友元的关键字为friend
友元的三种实现
全局函数做友元
类做友元
成员函数做友元

#include<iostream>
#include"swap.h"
using namespace std;
class person {
public: string m_b;
	  person() {
		  m_b = "客厅";
		  m_c = "卧室";
	  }
private:string m_c;
	  
	   friend void test(person* a); //全局函数做友元可以访问私有变量

};
void test(person *a) {
	cout << "全局函数正在访问" << a->m_b << endl;
	cout << "全局函数正在访问" << a->m_c << endl; //全局函数做友元可以访问私有变量
}
int main() {
	person p;
	test(&p);
	system("pause");
	return 0;
}

类做友元

#include<iostream>
#include"swap.h"
using namespace std;
class Building;
class GoodGay {
public: GoodGay();
public:
	void visit();
	Building* buliding;
};
class Building {
	friend class GoodGay;//类做友元
public: Building();
public: string sittingroom;
private: string bedroom;

};
Building::Building() {
	sittingroom = "客厅";
	bedroom = "卧室";
}
GoodGay::GoodGay() {
	buliding = new Building;
}
void GoodGay::visit() {
	cout << "好基友类正在访问" << buliding->sittingroom << endl;
	cout << "好基友类正在访问" << buliding->bedroom << endl;//类做友元能够访问私有属性
}
void test() {
	GoodGay gg;
	gg.visit();
}
int main() {
	test();
	system("pause");
	return 0;
}

成员函数做友元

#include<iostream>
#include"swap.h"
using namespace std;
class Building;
class GoodGay {
public: GoodGay();
	 void visit();
	 void visit1();
	Building* buliding;
};
class Building {
	friend void GoodGay:: visit1();
public: Building();
	  string sittingroom;
private: string bedroom;

};
Building::Building() {
	sittingroom = "客厅";
	bedroom = "卧室";
}
GoodGay::GoodGay() {
	buliding = new Building;
}
void GoodGay::visit() {
	cout << "visit函数正在访问" << buliding->sittingroom<< endl;
}
void GoodGay::visit1() {
	cout << "visit1函数正在访问" << buliding->sittingroom << endl;
	cout << "vist1函数正在访问" << buliding->bedroom << endl;
}
void test() {
	GoodGay gg;
	gg.visit();
	gg.visit1();
}
int main() {
	test();
	system("pause");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值