爱上c++的第四天(核心课程):类和对象--友元

116 阅读2分钟

你的c++学习路上明灯_哔哩哔哩_bilibili 上述是我在B站发布的相应视频

好吧,我承认了,我是懒虫,我其实很想狡辩一下,咳咳,还是好好认错吧。好久没有更新了,说实话,越玩越觉得空虚,还不如好好学习学习。

前两天看了一部两年前的电影,真的是很不错的,推荐给大家。

大学_电影_高清1080P在线观看平台_腾讯视频 (qq.com)https://v.qq.com/x/cover/mzc00200mts74tj/d0040jfkpzp.html

我觉得这个是一部很有教育意义的电影,真的体会到了什么叫做对那些伟大的学者的敬仰,什么叫做努力,什么叫做坚持,什么叫做对自己过往的悔恨。大家可以看一看。

好了,我们开始今天的学习。

目录

#一,友元

 ##一,全局函数做友元

##二,类做友元 

##三,成员函数做友元 


#一,友元

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

 ##一,全局函数做友元

#define _CRT_SECURE_NO_WARNINGS 1

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

class Building {
	//告诉编译器,GoodGay这个全局函数是Building类的友元
	friend void GoodGay(Building& p);
public:
	Building() {
		m_sitroom = "客厅";
		m_bedroom = "卧室";
	}
	string m_sitroom;
	
private:
	string m_bedroom;
};

void GoodGay(Building &p) {
	cout << "GoodGay正在访问:" << p.m_sitroom << endl;

	cout << "GoodGay正在访问:" << p.m_bedroom << endl;
}

void test1() {
	Building p;
	GoodGay(p);
}

int main() {

	test1();

	return 0;
}

##二,类做友元 

#define _CRT_SECURE_NO_WARNINGS 1

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

class Building {
	//用类做友元
	friend class GoodGay;
public:
	string m_sitroom;

	Building();
private:
	string m_bedroom;
};

class GoodGay {
public:
	void visit();//参观函数,访问Building中的属性

	Building* building=new Building;

};

//在类外写成员函数
//成员函数可以在类内写,也可以在类外写
Building::Building() {
	m_sitroom = "客厅";
	m_bedroom = "卧室";
}

void GoodGay::visit() {
	cout << "GoodGay正在访问:" << building->m_bedroom << endl;
	cout << "GoodGay正在访问:" << building->m_sitroom << endl;
}

void test1() {
	GoodGay gg;
	gg.visit();
}

int main() {
	test1();

	return 0;
}

##三,成员函数做友元 

#define _CRT_SECURE_NO_WARNINGS 1

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

class Building;
class GoodGay {
public:
	void visit();
	void visit2();//让第一个可以访问私有属性,visit2不行

	Building* building;//未定义Building类,所以要先声明,只有用成员函数做友元才需要,不懂为什么。用类做友元还不需要这么麻烦的。
	GoodGay();

};

class Building {
	//用成员函数做友元
	friend void GoodGay::visit();
public:
	string m_sitroom;

	Building();
private:
	string m_bedroom;
};

//在类外写成员函数
//成员函数可以在类内写,也可以在类外写
GoodGay::GoodGay() {
	building = new Building;
}
Building::Building() {
	m_sitroom = "客厅";
	m_bedroom = "卧室";
}

void GoodGay::visit() {
	cout << "GoodGay正在访问:" << building->m_bedroom << endl;
	cout << "GoodGay正在访问:" << building->m_sitroom << endl;
}

void GoodGay::visit2() {
	//cout << "GoodGay正在访问visit2:" << building->m_bedroom << endl;
	cout << "GoodGay正在访问visit2:" << building->m_sitroom << endl;
}

void test1() {
	GoodGay gg;
	gg.visit();
	gg.visit2();
}

int main() {
	test1();

	return 0;
}