栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 友元

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 友元

C++ 友元

文章目录
  • C++ 友元
  • 前言
  • 一、成员函数作为友元
  • 二、类作为友元
  • 三、全局函数作为友元
  • 本文章如有错误,欢迎指正!


前言

当你想在类的成员函数外部直接访问对象的私有成员时,C++ 就提供了友元(friend)的概念。在类中指定的友元就可以访问该类中受保护的内容。

一、成员函数作为友元

成员函数作为友元即为 类B 中的成员函数被 类A 视为友元,在这种情况下可以使用 类B 中被视为友元的函数访问 类A 中的受保护信息。

示例如下:

#include 
#include 

using namespace std;

class A;

class B{
public:
	B();

	void find_name();  //必须是处于 public 下的成员函数才能做为友元
	
	A *theA;
private:
	void find_id();   //该成员函数处于 private 下所以无法作为友元
};

class A{
	friend void B::find_name();
public:
	A();
private:
	string name;
	int id;
};
A::A(){
	name = "qwea";
	id = 10;
}
B::B(){
	theA = new A;
}

void B::find_name(){
	cout << theA->name << endl;
}

void test(){
	B theB;
	theB.find_name();
}

int main()
{
	test();
	return 0;
}

结果如下:

二、类作为友元

类作为友元即为 类B 将 类A 视为友元,在这种情况下,类A 中的方法都能访问 类B 中受保护元素。
代码如下(示例):

#include 
#include 

using namespace std;

class B;

class A{
public:
	A();
	void find_name();
	void find_id();
	
	B *theB;
};

class B{
	friend class A;  //将 类A 视为友元,使其内的方法能访问 类B 中受保护内容
public:
	B();
private:
	string name;
	int id;
};

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

B::B(){
	name = "qaz";
	id = 10;
}

void A::find_name(){
	cout << theB->name << endl;
}

void A::find_id(){
	cout << theB->id << endl;
}

void test(){
	A theA;
	theA.find_name();
	theA.find_id();
}

int main(){
	test();

	return 0;
}

结果如下:

三、全局函数作为友元

全局函数作为友元即为 类A 将一个 全局函数 视为友元,在这种情况下,该全局函数能访问到 类A 中受保护内容。
代码如下(示例):

#include 
#include 

using namespace std;

void find_NameAndId();

class A{
	friend void find_NameAndId(A theA);

public:
	A();

private:
	string name;
	int id;
};

A::A(){
	name = "tgh";
	id = 10;
}

void find_NameAndId(A theA){
	cout << theA.name << endl;
	cout << theA.id << endl;
}

int main(){
	A theA;

	find_NameAndId(theA);

	return 0;
}
		

结果如下:


本文章如有错误,欢迎指正!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/957853.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号