C++ 全局函数做友元

C++全局函数做友元 前言 友元 生活中你的家有客厅(Public),有你的卧室(Private) 客厅所有来的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去 但是呢,你也可以允许你的好闺蜜好基友进去。 在程序里,有些私有属性 也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术 友元的目的就是让一个函数或者类 访问另一个类中私有成员 友元的关键字为 friend 友元的三种实现 全局函数做友元 类做友元 成员函数做友元 全局函数做友元 class Building { //告诉编译器 goodGay 阅读详情
#include <iostream>
#include <string>
using namespace std;


/************************************************************************

友元
在程序里,类的私有属性也想让类外的一些特殊函数或类访问,就需要用到友元技术;
(就是让一个函数或类访问另一个类中的私有成员)

友元的三种实现
1.全局函数做友元,想访问哪个类的私有属性,就将该函数声明在类中,并加上friend关键字
2.类做友元
3.成员函数做友元

/************************************************************************/

class Building{
	
	// 将全局函数作为类的友元,这样就可以访问类的私有属性
	friend void good_friend(const Building& bld);
public:
	
	Building()
	{
		m_sitting_room = "客厅";
		m_bed_room = "卧室";
	}

	string m_sitting_room;
private:
	string m_bed_room;
};

void good_friend(const Building& bld)
{
	//类外可以正常访问类中的共有数据成员
	cout<<"sitting_room:"<<bld.m_sitting_room<<endl;

	//类中的私有成员类外无法访问,需要将该函数声明为类的全局友元函数
	cout<<"sitting_room:"<<bld.m_bed_room<<endl;

}

void test1()
{
	Building bld;
	good_friend(bld);
}


int main()
{

	test1();

	return 0;
}
C++全局函数做友元 - 让你的代码更加灵活 通过上面的例子,我们可以看到全局函数做友元的方法非常简单:只需要在类中声明友元函数,并在全局范围内定义该函数即可。当然,在实际开发中,我们不仅需要考虑代码的灵活性,也要注意代码的安全性,不要让全局函数随意访问类的私有成员变量或成员函数。它允许类中的特定函数或类可以访问其它类的私有成员变量或成员函数。但是,有时候我们需要在类之外定义一些函数,并让这些函数可以访问类的私有成员,那么怎么办呢?总之,全局函数做友元是 C++ 中非常有用的技巧,可以让我们的代码更加灵活和易于维护。,因为这个函数是 A 类的友元。 阅读详情

相关推荐

C++笔记之全局函数做友元与类做友元

【代码】C++笔记之全局函数做友元与类做友元。

小勇博客 385

C++ :全局变量(extern int a;)、全局函数【可跨文件/模块使用】【只在头文件中做“声明”】

所以我们可以得出结论:只在头文件中做声明!!!真理总是这么简单!

u013250861的博客 9664

AI辅助游戏开发实战:Kimi K3提升Unity开发效率与代码质量

在游戏开发领域,有限状态机(FSM)是构建角色AI行为逻辑的核心设计模式,它通过定义明确的状态和转换条件,使游戏实体能够智能地响应环境变化。其原理在于将复杂的行为分解为离散的状态节点,并通过事件驱动状态切换,从而实现清晰、可维护的AI架构。这项技术的价值在于显著提升了游戏角色的行为真实感和开发效率,被广泛应用于NPC行为控制、角色动画管理、UI流程等场景。随着AI编程助手的兴起,开发者现在可以借助如Kimi K3这类工具,通过自然语言指令快速生成和优化FSM等复杂系统的代码框架,将更多精力投入到核心玩法与性

weixin_30430677的博客 411

【C++ 函数 基本教程 第三篇 】深度解析C++函数类型:探寻全局函数、成员函数与静态函数的奥秘

在C++编程中,函数是我们编写代码的基础工具之一。它们帮助我们将复杂的问题分解为更小、更易于管理的部分。在C++中,我们主要有三种类型的函数:全局函数(Global Functions)、成员函数(Member Functions)和静态函数(Static Functions)。这些函数类型各有其特性和用途,理解它们的差异和适用场景对于编写高效、易于维护的代码至关重要。

探索C++编程的奥秘,分享深入的技术见解和实践,旨在激发读者创造力与解决问题的思维。 1998

SAP SD信贷管理实战:从配置到风险控制的完整指南(附后台路径)

本文详细解析了SAP SD信贷管理的完整配置流程与风险控制策略,涵盖信贷控制范围设置、风险分级机制及动态控制配置。通过实战案例和后台路径指引,帮助企业实现从客户信用评估到实时监控的全流程管理,有效降低坏账风险并优化资金安全。

3a9bq4r8t2y的博客 214

U-net复现pytorch版本 以及制作自己的数据集并训练

GitHub链接: https://github.com/milesial/Pytorch-UNet 论文链接:

candice5566的博客 3万+

C++学习之全局函数和成员函数

1.把全局函数转化成成员函数 通过this指针隐藏左操作数 Test add(Test &t1, Test &t2)===》Test add(Test &t2) 案例:实现 t1 = t1 + t2 class Test { public: Test(int a = 0, b = 0) { this->a = a; this->b =...

huhuhuhl的博客 9979

ZYNQ通过AXI DMA实现PL发送连续大量数据到PS DDR

方案二是在PS端的MPU配置中,将DMA缓冲区所在的内存区域标记为“不缓存”(Device或Strongly Ordered类型),但这样CPU访问这些内存区的速度会大幅降低,需要根据实时性和数据正确性的需求做权衡。更妙的是,描述符链表可以做成一个环状队列,放在DDR里让DMA循环取走,从而实现持续不断的“流式”传输。用FPGA实现FFT硬件加速的系统中也是如此:PS向PL提交待处理的FFT数据,PL硬件加速计算后,DMA把结果写回DDR,全程CPU几乎只做配置调度,大量数据吞吐留给了硬件通道。

QQ_778132974的博客 180

静态函数、全局函数,静态变量、局部变量、全局变量的作用域,生命周期,以及内存中的存储位置(C/C++):

局部变量: 局部变量也叫auto自动变量(auto可写可不写),一般情况下代码块{ }内部定义的变量都是自动变量,有如下特点: 在一个函数内定义,只在函数范围内有效; 在复合语句中定义,只在复合语句中有效; 随着函数调用的结束或复合语句的结束局部变量的的声明周期也结束; 如果没有赋值,内容随机。 静态局部变量: 在变量前面加上static关键字就是静态局部变量,有以下特点: static局部变量的作用域也是在定义的函数内部有效; static局部变量的生命周期和程序运行周期一样; .

weixin_46928280的博客 4044

在 SAP 中实现“租赁资产”管理,核心是把 IFRS16/ASC842 等新租赁准则的要求落地到系统

摘要:本文详细介绍了在SAP S/4HANA系统中实现IFRS16/ASC842租赁准则的具体操作流程。主要内容包括:1) 系统前置配置,如激活租赁会计组件、定义租赁类型和会计科目;2) 租赁合同创建与主数据维护;3) 初始确认的会计处理;4) 日常折旧计提和租金支付流程;5) 合同变更与终止管理。通过RE-FX-LM模块与固定资产模块的集成,系统可自动生成使用权资产和租赁负债,支持从合同创建到报表披露的全生命周期管理,确保符合新租赁准则要求。

金牌架构师 988

ARINC429协议分析

如下表所示,ARINC429在发送一帧过程中,首先发送以START开始,以END结束,共发送32bits数据,其中0~7bits为Lable数据,9~8bits为SDI数据,10~28bits为数据,29~30bits为SSM,31bit为校验位End30292827262524校验位SSM2322212019181716DATA15141312111098SDI7654321Start。

5225

C++ 定义全局函数——一处定义全局使用

利用头文件来实现全局变量一次声明全文件使用。

m0_38036750的博客 5871

如何使用手机编程查看妻子的微信

在本文中,我将向您介绍如何使用编程技巧来查看妻子的微信消息。请注意,隐私是非常重要的,因此在进行此类操作之前,请确保您已经获得了妻子的明确许可。此外,请记住,未经对方授权访问他人的通信是违法行为,因此请谨慎行事。请记住,这仅仅是使用编程技巧来查看妻子的微信消息的一种方法。itchat是一个用于微信个人账号的API,可以通过Python编程语言与微信进行交互。一旦我们登录成功,我们可以使用itchat库获取妻子的微信好友列表。我们可以使用itchat库来查看妻子的微信消息。步骤 5:查看妻子的微信消息。

TechPulseZ的博客 461

C++友元的三种类型(全局函数做友元,友元类,成员函数做友元)

本文详细介绍了有关友元的一些说明:友元的定义(友元是什么?)、友元的作用、友元的分类及具体实现、创建时的注意事项。以上就是本文的所有内容,友元的主要目的是提供更灵活的访问控制,以便在某些情况下,外部函数或类能够直接操作类的内部数据,当我们需要使用到友元时,我们只需要在类中提前声明就可以,声明时通常是,在前面加关键字friend。

weixin_48452146的博客 1395

多智能体强化学习MATD3算法完整复现与分析

多智能体强化学习MATD3算法复现与分析摘要 MATD3算法是多智能体深度强化学习领域的重要进展,通过改进MADDPG算法,引入双Q学习、延迟策略更新和目标策略平滑等技术,显著提升了算法稳定性。本文完整复现了MATD3算法,详细解析了其数学原理,包括部分可观测马尔可夫博弈模型和TD3核心思想。在实现层面,设计了集中式Critic和分布式Actor的神经网络架构,采用PyTorch框架构建了Actor-Critic网络模块,包含精心设计的权重初始化和训练流程。该算法有效解决了多智能体环境中的非平稳性、信用分配

max500600的博客 540

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

什么是友元?什么可以做友元?友元能干什么?(全局函数做友元,类做友元,成员函数做友元)c/c++

例如:你的生活中有一个特别好的朋友,你允许它进入你的房间(私有场所)也允许他进入客厅(相对公有场所),但是对于其他人你是不会允许他进入你的房间的,只允许他进入客厅。类对象也有这样类似的好朋友类,可以访问本类的私有成员,这个好朋友类就叫做这个类的友元,友元也可以是全局函数和别的类的成员函数,下面一一解答。

m0_57094953的博客 1620

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C++友元->全局函数做友元、类做友元、成员函数做友元

/只让visit函数作为Building的好朋友,可以访问Building中私有成员。cout << "好基友正在访问" << building->m_SittingRoom << endl;cout << "好基友正在访问" << building->m_SittingRoom << endl;cout << "好基友正在访问" << building->m_SittingRoom << endl;//cout << "好基友正在访问" << building->m_BedRoom << endl;

鲸鱼的博客 1105

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

C++_核心编程_友元_全局函数做友元_类做友元_成员函数做友元

【代码】C++_核心编程_友元_全局函数做友元_类做友元_成员函数做友元。

leijinquan01的博客 131

【C++编程语言】之 全局函数做友元 类做友元 ​成员函数做友元

生活中你的家有客厅(public),有你的卧室(private)。客厅所有来的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去,但是呢,你也可以允许你的好闺蜜好基友进去。在程序里,有些私有属性,也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术。友元的目的就是让一个函数或者类访问另一个类中私有成员。​ 1.全局函数做友元。​ 3.成员函数做友元。

kaszxc的博客 407

[C++ 核心编程]笔记 4.4.1 全局函数做友元

概述:生活中你的家有客厅(Public),有你的卧室(Private)客厅所有来的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去, 但是呢,你也可以允许你的好闺蜜好基友进去。friend友元的三种实现。

Alex的博客 468

c++基础(十三)——全局函数做友元

友元可以让一些私有属性被类外特殊的一些函数或者类进行访问,换句话说,友元的目的就是让一个函数或者类访问另一个类中私有成员。友元的关键字为:friend。

qq_52302919的博客 999

C++中全局函数做友元

#include <iostream> using namespace std; #include <string> //全局函数做友元 //建筑物类 class Building { friend void goodGay(Building *building); public: Building() { m_SittingRoom = "客厅"; m_BedRoom = "卧室"; } public: string m_Sitti.

weixin_62539876的博客 851

C++类和对象-友元(全局函数做友元,友元类,成员函数做友元)

生活中你的家有客厅(rublic),有你的卧室(Private)客厅所有来的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去但是呢,你也可以允许你的好闺蜜好基友进去。在程序里,有些私有属性 也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术友元的目的就是让一个函数或者类 访问另一个类中私有成员友元的关键字为friend友元的三种实现全局函数做友元类做友元成员函数做友元。

qq_63055790的博客 379

C++2类和对象 友元 全局函数做友元 类做友元 类内成员函数做友元

友元函数 简介:在程序里面有些私有属性也想让类外的函数或类去访问,就需要用到友元函数。友元的目的就是让一个函数或类的成员去访问另一个类的私有成员。如同两个陌生人强制建立友谊,瞬间感情升温变成好朋友。 关键字:friend 用三个程序解释三种方法 1.全局函数做友元 #include"iostream" using namespace std; class Person { friend void friend_people(Person *p); public: string y_name="ya

weixin_44176501的博客 353

【C++核心编程 4】——类和对象——4.4 友元[ 全局函数做友元 / 类做友元 / 成员函数做友元 ]

全局函数做友元 / 类做友元 / 成员函数做友元

my优快云3657的博客 255
上一篇: C++ 常函数和常对象
下一篇: C++ 类友元和成员函数友元
最后冰吻free
博客等级 码龄12年 121粉丝 371原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值