C++中struct和class的区别

C/C++ 专栏收录该内容
¥99.90 ¥299.90
204篇文章

C++中struct和class的区别

C++中的struct和class是两种主要的数据类型,它们在使用时往往会混淆。本文将详细介绍struct和class的区别,为大家解决困扰。

一、基本概念

首先,让我们了解一下struct和class的基本概念。C++中的struct和class都可以用来定义自定义数据类型,这些类型可以由用户自行定义数据成员和成员函数。

struct和class的最大区别在于默认的访问级别不同。在struct中,默认的访问级别是公共的(public),而在class中则是私有的(private)。

因此,当我们想要拥有私有的数据成员和成员函数,建议使用class。当我们想简单定义一个结构体,不需要过多限制访问权限,可以使用struct。

二、代码示例

接下来,为了更好地说明struct和class的区别,我们来看一个代码示例。

// struct示例
struct Person {
    std::string name;
    int age;
};

// class示例
class Student {
public:
    std::string name;
    int age;
private:
    float grade;
};

在上述代码中,我们声明了一个Person结构体和一个Student类。注意到,在Person中,我们没有指定任何访问级别,因此默认为公共。而在Student中,我们通过public关键字指定了name和age为公共访问级别,而grade则被指定为私有访问级别。

三、使用注意

在使用st

C++中struct与class的核心区别与应用场景 在面向对象编程中,访问控制是实现封装的关键机制。C++通过public、private等访问修饰符控制成员可见性,其中struct和class作为类型定义的核心关键字,其默认访问权限的差异直接影响工程实践。从编译器角度看,二者生成的机器码完全相同,主要区别在于struct默认成员为public,而class默认为private,这种设计使得struct更适合作为数据载体或与C语言交互,而class更擅长封装复杂对象行为。在模板元编程和跨语言交互场景中,struct因其默认公开特性常被用于特性萃取和接口定义。 阅读详情

相关推荐

C++struct和class区别

在C++中 struct和class唯一的区别就在于 默认的访问权限不同 区别: struct 默认权限为公共 class 默认权限为私有 class C1 { int m_A; //默认是私有权限 }; struct C2 { int m_A; //默认是公共权限 }; int main() { C1 c1; c1.m_A = 10; //错误,访问权限是私有 C2 c2; c2.m_A = 10; //正确,访问权限是公共 system("pause"); ret

希望我的博客,能帮上你解决学习中工作中所遇到的问题 714

从Reset到Read:深入解析Rolling Shutter曝光流水线

本文深入解析Rolling Shutter(卷帘曝光)的工作原理,重点探讨Reset和Read信号在图像传感器中的关键作用。通过Reset-Read流水线机制,详细解释了曝光控制、时序调优及运动伪影补偿等核心技术,帮助读者理解卷帘曝光在高速摄影和动态场景中的应用。

weixin_42531925的博客 266

GmSSL国密双证书实战:从生成到Nginx配置全流程

本文详细介绍了使用GmSSL工具生成国密双证书(签名证书与加密证书)并配置Nginx支持国密HTTPS(TLCP协议)的全流程。内容涵盖环境准备、自签CA创建、服务器双证书生成、Nginx单向/双向认证配置以及兼容性处理,为部署符合国密标准的HTTPS服务提供实战指南。

weixin_29276847的博客 484

别只会‘pip install’了!当Python报错找不到‘pkg_resources’时,你的setuptools可能出大问题

本文深入解析Python开发中常见的`ModuleNotFoundError: No module named 'pkg_resources'`错误,揭示其背后的setuptools依赖问题。通过系统化的诊断与修复指南,帮助开发者理解Python包管理机制,并提供从基础到高级的解决方案,确保pip和setuptools的正常运行。

weixin_42523711的博客 439

USB 网卡——RNDIS 控制消息流程

在其控制端点上获取控制消息时,设备必须在通信类接口的中断 IN 端点上返回通知,每当设备可以返回控制消息时,主机就会轮询该通知。需要注意的是,如果设备由于某种原因收到GET_ENCAPSULATED_RESPONSE,并且无法使用控制端点上的有效数据做出响应,则应返回设置为 0x00 的单字节数据包,而不是 stall 控制端点。下表中定义了此传输。收到 RESPONSE_AVAILABLE 通知后,主机使用下表中定义的GET_ENCAPSULATED_RESPONSE 传输从控制端点读取控制消息。

tyustli 378

⚡【C++要笑着学】(13) STL介绍:什么是STL标准模板库 | STL的版本 | 浅谈STL的缺陷

再讲解函数模板之前先对STL做一个小铺垫,本篇将对STL做一个简单的介绍。

有道无术, 术尚可求。有术无道, 止于术。 3044

YOLO11改进-注意力-引入自调制特征聚合模块SMFA

SMFA(自调制特征聚合模块): SMFA模块用于协同建模局部和非局部信息,它分为两个分支:一个是EASA(Efficient Approximation of Self-Attention,简化的自注意力分支),用于捕获非局部信息;另一个是LDE(Local Detail Estimation,局部细节估计分支),用于捕获局部细节。EASA通过对输入特征进行下采样,然后利用全局特征的方差进行调制,再与原始特征进行聚合,提取非局部结构信息。LDE分支则通过卷积操作提取输入特征中的高频局部信息。

qq_64693987的博客 2217

【EB-02】TC397 Tresos 最小工程配置

主要设置McalLibPublishedInformation 参数,会根据ResourceM配置的芯片自动加载。可以看到再工程目录中生成了output文件夹,里面由这些模块生成的头文件,编译脚本和epc文件。如果选择生成swcd,可以生成xxx_Bswmd.arxml给别的工具使用。如果没有Error和Problems就可以点击生成代码。点击工程校验看看工程是否由错误。

libuping2023的博客 331

eCognition易康操作教程(二):多尺度分割基于多光谱数据构建规则集,结合DSM高程数据提取建筑物、树木和绿地

一、数据 数据来源:教程中的实验数据,共包含RGB三个波段,还有数字地表模型(以下简称DSM)文件。 图一 RGB影像 数据特征:数据范围较小,要素种类少,仅包含较多的建筑和大片的绿地。由于建筑的房顶使用的材料和材料颜色不同,所以建筑的光谱特征没有规律,是不连续的特征。而绿地的光谱特征则十分容易分辨。 但是建筑通常具有规则的形状,而且建筑相比于周围其他要素...

蒹葭苍苍 8312

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

深度学习工具包 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++ 操作符优先级详解
下一篇: 调试Qt Quick应用程序
普通网友
博客等级 码龄4年 1011粉丝 1742原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编码实践

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址