友元函数和友元类

C++友元函数和友元类 阅读详情

私有成员只能在类的成员函数内部访问,如果想在别处访问对象的私有成员,只能通过类提供的公有接口(成员函数)间接地进行。

这固然能够带来数据隐藏的好处,利于将来程序的扩充,但也会增加程序书写的麻烦。

一. 友元函数

在定义一个类的时候,可以把一些函数声明为“友元”,这样那些函数就成为该类的友元函数。

友元函数是在类中用关键字friend修饰的非成员函数,可以是一个普通的函数,或是其它类的成员函数。

它不是本类的成员函数,却在它的函数体中却可以访问类的私有成员和保护成员。

将全局函数声明为友元的写法如下:

friend  返回值类型  函数名(参数表);

将其他类的成员函数声明为友元的写法如下:

friend  返回值类型  其他类的类名::成员函数名(参数表);

例如:

#include<iostream>
using namespace std;
class CCar;  //提前声明CCar类,以便后面的CDriver类使用
class CDriver
{
public:
    void ModifyCar(CCar* pCar);  //改装汽车
};
class CCar
{
private:
    int price;
    friend int MostExpensiveCar(CCar cars[], int total);  //声明普通友元
    friend void CDriver::ModifyCar(CCar* pCar);  //声明其他类的友元
};
void CDriver::ModifyCar(CCar* pCar)
{
    pCar->price += 1000;  //汽车改装后价值增加
}
int MostExpensiveCar(CCar cars[], int total)  //求最贵气车的价格
{
    int tmpMax = -1;
    for (int i = 0; i<total; ++i)
        if (cars[i].price > tmpMax)
            tmpMax = cars[i].price;
    return tmpMax;
}

二. 友元类

一个类 A 可以将另一个类 B 声明为自己的友元,类 B 的所有成员函数就都可以访问类 A 对象的私有成员。

class CCar
{
private:
    int price;
    friend class CDriver;  //声明 CDriver 为友元类
};
class CDriver
{
public:
    CCar myCar;
    void ModifyCar()  //改装汽车
    {
        myCar.price += 1000;  //因CDriver是CCar的友元类,故此处可以访问其私有成员
    }
};
友元类和友元函数 文章目录Friend class and function in C++Friend classFriend function注意事项 Friend class and function in C++ Friend class Friend Class. 友元类可以是另一个类访问当前类的私有数据和方法. 如下例: class Node { private: int key; Node *n... 阅读详情

相关推荐

C++友元函数和友元类用法详解

在C++中,我们使用类对数据进行了隐藏和封装,类的数据成员一般都定义为私有成员,成员函数一般都定义为公有的,以此提供类与外界的通讯接口。但是,有时需要定义一些函数,这些函数不是类的一部分,但又需要频繁地访问类的数据成员,这时可以将这些函数定义为该函数的友元函数。除了友元函数外,还有友元类,两者统称为友元。友元的作用是提高了程序的运行效率(即减少了类型检查和安全性检查等都需要时间开销),但它破坏了类

程序猿老樊的博客 7万+

C++友元函数,友元类

1. 友元的声明只能出现在类的内部,但是在类内出现的具体位置不限制,友元函数不是类的成员 也不受所在区域访问控制级别的限值 2. 友元函数的定义可以在类内也可以在类外 3. 友元函数它不是成员函数,它不受作用域的限值,不属于类,也不属于对象,他就是一个普通的函数 友元函数使用典型错误: <wiz_code_mirror> ...

weixin_30457065的博客 273

Bentley二次开发教程28-交互窗口-案例实战2-EC属性赋值工具

该工具会根据用户输入的路径获取Schema文件的路径,然后通过路径读取对应的Schema文件并在树状图中显示EC类,当用户选择树状图上的节点时,此时会触发事件,根据EC属性添加用户自定义控件用于显示EC属性并可对其进行赋值操作。完成后选取元素,点击界面上的应用,此时元素会被赋予指定EC类,同时修改的EC属性值也会被同步赋予。该工具涉及到的WinForm控件有:TextBox,Button,TreeView,Panel,UserControl(用户自定义控件)。

不见不散的博客 1475

友元

友元有三种:友元类,友元函数,友元成员。 友元函数 注意: (1)友元函数也可以在类内定义 ,但是友元函数并不是类的成员函数,而是不属于任何类的一般外界函数。 (2)同理友元函数没有this指针,必须使用对象名。成员名进行访问 友元成员: 友元成员可以被认为是一个类的成员函数被声明为另一个类的的成员函数 friend 类名::成员函数名; 注意: (1)友元不具有传递性。(A是B的友元,B是C的友元,A不是C的友元) (2)友元是单向的。 (3)友元的声...

qq_62845624的博客 1630

STM32F103ZET6【标准库函数开发】------04五个串口配置实战:从零到一构建多串口通信系统

本文详细介绍了STM32F103ZET6标准库函数开发中五个串口(USART/UART)的配置实战,从硬件引脚识别、时钟树配置到多串口系统整合技巧。通过具体代码示例和调试经验,帮助开发者快速构建稳定的多串口通信系统,适用于工业控制、物联网网关等应用场景。

weixin_29188997的博客 344

KEPServer EX6的Modbus、MQTT和REST Server一站式配置整理说明

KEPServer EX6的Modbus、MQTT和REST Server一站式配置整理说明

syqenter的专栏 8962

【C++】类和对象:友元函数和友元类

友元函数和友元类

qq_46403377的博客 782

Excel插件开发实战:从零封装一个带自定义Ribbon的.xlam工具包

本文详细介绍了如何从零开发一个带自定义Ribbon的Excel插件.xlam工具包。通过VBA和XML技术,读者将学习到插件架构设计、Ribbon界面定制、模块化开发以及企业级部署策略,帮助提升Excel自动化办公效率。

weixin_42531128的博客 517

C++中类的友元函数和友元类详解

类的友元函数是定义类外部,但是有权限访问类的所有私有(private)成员和保护(protected)成员。友元函数并不是类成员函数。友元可以是一个函数,也可以是一个类,我们称之为友元类,整个类及其所有成员都是友元。我们通过一个例子来认识友元函数: 1.2 友元类 友元类的所有成员函数都是另一个类的友元函数,都可以访问另一个类中的隐藏信息(包括私有成员和保护成员),友元类固然好用,但是它打破了面向对象的封装特性。我建议尽量不要用或者少用。我们举例说明一下:main.cpp 2.说明 友元函数是类外函数,声

weixin_45805339的博客 963

CS231n+assignment2(一)

cs231n作业二详解+代码

qq_56551150的博客 2411

开源免费!ReaLTaiizor如何用MIT许可证打造专业级WinForm UI?

摘要: ReaLTaiizor是一款开源UI控件库,为WinForm应用提供现代化界面解决方案。支持100+组件、多主题切换(浅色/深色/自定义)和.NET 4.8-8.0全版本兼容,MIT许可证允许免费商用。通过NuGet快速安装,3步改造传统界面:1)注入主题(如this.Theme = new Dark()),2)替换原生控件为高颜值组件(如ModernGrid替代DataGridView),3)集成高级功能(分页/动画提示)。典型场景包括登录界面美化(进度动画+通知控件)和数据表格Material风

墨夶的博客 1521

C++友元 friend

友元 友元的作用 友元,就是类似好朋友一样的存在,其他人进不来你的私密(private)处,但是友元可以。 能做友元的对象 全局函数做友元 类做友元 成员函数做友元 全局函数做友元 平常情况(全局函数不是友元) #include<iostream> #include<string> using namespace std; class Room { public: string public_place; private: string private_place; };

milaiko的博客 227

OpenHarmony + AI:深度解析 Whisper.cpp 智慧语音系统级移植与 NAPI 封装实战

【代码】OpenHarmony + AI:深度解析 Whisper.cpp 智慧语音系统级移植与 NAPI 封装实战。

m0_67505153的博客 188

[C++]友元函数和友元类

友元函数是非成员函数,但被允许访问类的私有成员。通过friend关键字声明友元函数,它可以访问类的私有数据。友元函数并不是类的成员,它只能访问类的私有和保护成员,而不能访问类的其他成员函数或成员变量。友元函数的访问权限仅限于该类的私有和保护成员。友元类是允许访问另一个类私有成员的类。通过关键字声明友元类,使得友元类的成员函数能够访问被声明类的私有数据。友元类和继承关系不同,它只是授权给一个类访问另一个类的私有成员,不会影响类的继承关系。

2302_80281315的博客 1063

芒果YOLO11改进106:检测头篇DynamicHead动态检测头:基于DynamicHead,二次原创提出SATNeXt模块,提出全新的动态DynamicSatDetect

检测头篇DynamicHead动态检测头:基于DynamicHead,二次原创提出SATNeXt模块,提出全新的动态DynamicSatDetect

包括YOLOv5、YOLOv7、YOLOv8等模型改进 773

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

C++的友元函数和友元类

6.C++的友元函数和友元类 1.什么是友元函数 1.1、外部函数访问类内成员 (1)写一个Person类,内部有private、protected、public的三类访问权限的成员 (2)写一个外部函数disp_info来打印这三类成员 (3)代码实战 (4)总结:可以访问public的,但是protected和private的无法访问 (5)想办法:除非把disp_info挪到Person类内部成为成员函数,否则没办法 1.2、友元函数的引入 (1)将外部函数disp_info声明为Person类的友元

weixin_44705391的博客 764

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

C++友元函数和友元类!

标题看起来有点拗口,但是却很好的解释了,这个友元函数定义和声明的状态?闲话少说,直接看代码public://构造函数public://将show()声明为类Student的友元函数private:int m_age;//非成员函数cout<<pstu->m_name<<"的年龄是 "<<pstu->m_age<<",成绩是 "<<pstu->m_score<<endl;Student stu("小明", 15, 90.6);show(&stu);//调用友元函数。

WE_BIG的博客 730

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

深度学习工具包 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")

【牛客网】—— 友元函数和友元类

今天在牛客网刷题的时候遇到这样一个题,和大家分享一下 这道题我做错了,看完解析之后还是有些似懂非懂,于是去查看了一些友元函数和友元类的相关资料,给大家分享一下,首先我们先来分析一下这个题: A:在C++中友元函数是独立于当前类的外部函数 B:一个友元函数可以同时定义为两个类的友元函数 C:友元函数既可以在类的内部,也可以在类的外部定义; D:在外部定义友元函数时,不必加关键字friend 友...

chenxiyuehh的博客 2325

c语言的友元函数的用法,C++友元函数和友元类概念解析

一、友元函数友元函数是一种特殊的函数,它需要在类体内进行说明,可以访问类的私有成员和保护成员,但又不是类的成员函数。友元函数的说明如下:friend 数据类型函数名(参数)其中,friend是说明友元函数的关键字,友元声明可以出现在类中的任何地方。通常,将友元声明成组地放在类定义的开始或结尾是个好主意。归纳起来,友元函数是一种能够访问类中私有成员的非类成员函数,友元函数在定义上和调用上与普通函数...

weixin_29596051的博客 2020
上一篇: Linux 学习笔记 (8) —— tty,ulimit -a
下一篇: etc —— (1)
Candyerer
博客等级 码龄7年 20粉丝 40原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值