c++: C++中的explicit

C++中的explicit详解 C++ explicit关键字详解 首先, C++中的explicit关键字只能用于修饰只有一个参数的类构造函数, 它的作用是表明该构造函数是显示的, 而非隐式的, 跟它相对应的另一个关键字是implicit, 意思是隐藏的,类构造函数默认情况下即声明为implicit(隐式). 那么显示声明的构造函数和隐式声明的有什么区别呢? 我们来看下面的例子: class CxString // 没有使用... 阅读详情

定义

C++中, 一个参数的构造函数(或者除了第一个参数外其余参数都有默认值的多参构造函数), 承担了两个角色:

    1. 是个构造器
    1. 是个默认且隐含的类型转换操作符。

所以, 有时候在我们写下如 AAA = XXX, 这样的代码, 且恰好XXX的类型正好是AAA单参数构造器的参数类型, 这时候编译器就自动调用这个构造器,创建一个AAA的对象。
这样看起来好象很酷, 很方便。 但在某些情况下(见下面权威的例子), 却违背了我们(程序员)的本意。
这时候就要在这个构造器前面加上explicit修饰, 指定这个构造器只能被明确的调用/使用, 不能作为类型转换操作符被隐含的使用。
explicit构造函数的作用

实例

explicit构造函数是用来防止隐式转换的。请看下面的代码:

class Test1
{
public:
    Test1(int n)
    {
        num=n;
    }//普通构造函数
private:
    int num;
};
class Test2
{
public:
    explicit Test2(int n)
    {
        num=n;
    }//explicit(显式)构造函数
private:
    int num;
};
int main()
{
    Test1 t1=12;//隐式调用其构造函数,成功
    Test2 t2=12;//编译错误,不能隐式调用其构造函数
    Test2 t2(12);//显式调用成功
    return 0;
}

注释

Test1的构造函数带一个int型的参数,代码23行会隐式转换成调用Test1的这个构造函数。而Test2的构造函数被声明为explicit(显式),这表示不能通过隐式转换来调用这个构造函数,因此代码24行会出现编译错误。
普通构造函数能够被隐式调用。而explicit构造函数只能被显式调用。

C++中的关键字explicit 最近在复习QT,准备做项目了,QT Creator 默认生成的代码 explicit Dialog(QWidget *parent = 0)中,有这么一个关键字explicit ,用来修饰构造函数。以前在Windows下写程序的时候,基本上没有碰到这个关键字,那么这个关键字是做 阅读详情

相关推荐

理解C++中的explicit关键字

在编程语言中,类型转换是指将变量从一种数据类型转换为另一种数据类型的过程。类型转换可以是显式的,也可以是隐式的。显式类型转换由程序员通过特定的语法明确指定,而隐式类型转换则由编译器在编译时自动进行,无需程序员的明确指示。类型转换通常分为两类:安全的类型转换和不安全的类型转换。安全的类型转换,如将整数赋值给更大的整数类型,不会导致数据丢失。不安全的类型转换,例如将浮点数赋值给整数类型,可能会导致精度损失或意外的行为。在C++编程中,explicit。

weixin_42527589的博客 1007

error C2536:'std::pair::first' :cannot specify explicit initializer for arrays

当与到这种错误的时候,是因为模板使用出错比如:std::make_pair("abc","123");这样时便会出现error C2536:'std::pair::first' :cannot specify explicit initializer for arrays正确的使用方法是:std::make_pair(string("abc"),string("123"))希望对读者有用!...

yuchu123456的博客 2350

STM32CubeIDE无法连接STLinkV2的一个可能原因

前些日子买了个新的STLINKV2 , ( 老的被我家猫猫一泡尿送上西天了)刚开始还挺正常的, 后来有一天就突然间发现无法调试了.网上尝试了各种方法, 各种操作. 百度了好久. 最后好在我自己研究出来了.我使用的是 STM32CubeIDE 这个开发工具调试选项如下图其它的不需要修改, 然后点击下面的apply 按钮, 然后调试Debug, 提示 No STLink 如下图后来尝试了下载ST-LINK Utility 用它是可以正常连接STLink的, 然后也能正常进行升级操作.

走错路的程序员 9822

The Constructor Initializer in c++

  class   A     {     public:     A():a({1,2})       {       };     private:     const   int   a[2];     };         编译过不了!请帮忙解释一下,谢谢 解释:1.类里面的任何成员变量在定义时是不能初始化的。     2.一般的数据成员可以在构造函数中初始化。     3

k的专栏 2744

MediaCodec视频解码流程详解及参考demo

本文主要讲解mediacodec的视频解码流程,及demo参考例子。

分享音视频技术 7872

Unity零基础到入门☀️| 万字教程 讲解Unity中的数据存储 PlayerPrefs、XML、JSON【建议收藏】

本文章是Unity零基础到入门专栏的系列文章。 适合对Unity3D引擎感兴趣的小伙伴学习,偏向于新手学习! 本篇文章就来介绍一下Unity中三种基本的数据存储方式:PlayerPrefs、XML、JSON

努力前行,总会成为自己心中的那道光 8万+

继承与派生 编程题#2: 魔兽世界之二:装备(Coursera 程序设计与算法 专项课程3 C++程序设计 郭炜、刘家瑛;OpenJudge)

编程题#2: 魔兽世界之二:装备来源: POJ (http://cxsjsxmooc.openjudge.cn/test/E/)注意: 总时间限制: 1000ms 内存限制: 65536kB描述 魔兽世界的西面是红魔军的司令部,东面是蓝魔军的司令部。两个司令部之间是依次排列的若干城市。 红司令部,City 1,City 2,……,City n,蓝司令部 两军的司令部都会制造武士。武士一共有 d

小勇工作室 1235

【DRAM存储器六十九】DDR5介绍--2N mode 和 CS Geardown mode

摘要: DDR5内存速率提升至8400MT/s以上时,信号完整性成为关键挑战。JEDEC在JESD79-5B标准中引入2N Mode和CS Geardown Mode两项技术,通过“时间换稳定性”优化时序裕量。2N Mode默认启用,将命令周期延长至两倍时钟周期,增强全局命令稳定性;CS Geardown Mode则针对片选信号(CS_n)降低采样频率,提升局部信号容错能力。两者均需通过特定寄存器配置,适用于高频场景下的性能与稳定性平衡。这些技术为DDR5在高频运行中提供了可靠的时序保障。

highman110的博客 214

我谈给类成员数组进行大批赋值的方法 (转)

我谈给类成员数组进行大批赋值的方法 (转)[@more@]今天上qq,有一个朋友问我怎么样给一个类的成员变量[是数组]赋初值。比如:class CTest{private:int m_arr[10];……}; 如果想给成员...

csd3176的博客 320

一文吃透 SAP IDoc 状态码:从 TEDS1 到 WE02 排障,再到 ABAP 自动化监控

在 SAP 集成场景里,IDoc 往往是最常见、也最容易被低估的一条生命线:采购订单、发票、主数据、库存移动……只要系统之间要稳定地交换结构化业务数据,IDoc 就经常登场。真正让人头疼的,并不是 IDoc 本身,而是它在链路里到底走到了哪一步、卡在了哪里、该找谁背锅。这篇文章把常用的 IDoc 状态码按出站、入站拆开讲清楚,并且把每个状态对应的真实世界故障现象、排查入口、以及可以落地的 ABAP 监控代码串起来,让你看到状态码就能想到动作。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 404

淘宝母婴用品数据挖掘及可视化分析研究

1. 背景介绍 在当今的电子商务时代,母婴用品市场已经成为了各大电商平台的一片蓝海。淘宝作为中国最大的电子商务平台,其上的母婴用品交易数据自然引人关注。理解这些数据,可以帮助商家更好地制定营销策略,也可以帮助消费者更好地选择产品。因此,本文将对淘宝母婴用品的数据进行深入的挖掘和分析。 1.1 电子商务的

AI天才研究院 1253

c++易错点总结(1): cpp中的explicit的作用,为何尽量使用explicit关键字

在c++种explicit关键字只能用来修饰构造函数。禁止它自动调用拷贝初始化。 什么是拷贝初始化?举个例子: 现在我们不使用explicit关键字看看会发生什么?我们发现下面这个代码明明我们给函数f()传递的参数是一个整数,但是编译器却自动调用了类A的构造函数,这种就叫做拷贝初始化。这是超出预期的。如果你不希望这样那么请在构造函数前面加上explicit关键词禁止编译器这种自动调用拷贝初始化的行...

@司南牧|知乎|博客|易懂教程|李韬 1527

第一篇:APS智能排产理论核心与求解器选型指南

本文系统解析了APS(高级计划与排程)系统的核心功能与技术实现。APS作为融合生产计划与排程的智能决策系统,通过运筹优化算法实现全局最优,平衡交付与效率。重点探讨了混合整数线性规划(MILP)在APS中的应用,包括设备分配、生产批量和人员班次优化等场景,并分析了其局限性与其他算法(如启发式算法)的互补性。文章还提供了APS实施策略建议和优化建模技巧,强调从简单模型开始迭代验证的重要性。最后介绍了甘特图在APS中的多维可视化作用,包括计划调整和决策支持功能。全文为理解APS系统原理及实践应用提供了全面指导。

算法工程师 544

C++中的explicit关键字

C++中的关键字explicit主要是用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换,只能以显示的方式进行类型转换。类构造函数默认情况下声明为隐式的即implicit。 隐式转换即是可以由单个实参来调用的构造函数定义了一个从形参类型到该类类型的隐式转换。编译器在试图编译某一条语句时,如果某一函数的参数类型不匹配,编译器就会尝试进行隐式转换,如果隐式转换后能正确编译,编译器就会继续执行编译过程,否则报错。 explicit关键字只能用于类内部的构造函数声明上,...

姜的理想国 611

深度学习工具包 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++中的explicit关键字介绍

C++中的关键字explicit主要是用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换,只能以显示的方式进行类型转换。类构造函数默认情况下声明为隐式的即implicit。 隐式转换即是可以由单个实参来调用的构造函数定义了一个从形参类型到该类类型的隐式转换。编译器在试图编译某一条语句时,如果某一函数的参数类型不匹配,编译器就会尝试进行隐式转换,如果隐式转换后能正确编译,编译器就会继续执行编译过程,否则报错。 explicit关键字只能用于类内部的构造函数声明上,而...

clark的专栏 569

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Qt C++中的关键字explicit

最近在复习QT,准备做项目了,QT Creator 默认生成的代码 explicit Dialog(QWidget *parent = 0)中,有这么一个关键字explicit ,用来修饰构造函数。以前在Windows下写程序的时候,基本上没有碰到这个关键字,那么这个关键字是做什么用的呢?       关键字 explicit 可以禁止“单参数构造函数”被用于自动类型转换。光看这一句似乎不太容

2万+

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

c++中的explicit

1. 作用 用来修饰类的成员函数,只能显式的进行类型转换。 2. 注意要点 1)explicit关键字只能用于类内部的构造函数或转换构造函数(c++11起)或推导指南(c++17起),被修饰的构造函数不能发生隐式转换或复制初始化; 2)只能作用于单个参数的构造函数。如构造函数有多个参数,但除了第一个参数其他均默认为0,也可以起作用(如下面的例子); 3. 代码示例 Test类未被explicit修饰 class Test { public: Test(int x = 0, int y =

www_dong的博客 373

【C++】C++中的explicit关键字详解

c++提供了关键字explicit,禁止通过构造函数进行的隐式转换。声明为explicit的构造函数不能在隐式转换中使用。注意explicit用于修饰构造函数,防止隐式转化。是针对单参数的构造函数(或者除了第一个参数外其余参数都有默认值的多参构造)而言。} M//给字符串赋值?还是初始化?//隐式//显示//寓意非常明确,给字符串赋值return 0;

qq_35902025的博客 1069
上一篇: 路径规划: PRM路径规划算法
下一篇: c++: c++ unique_ptr使用
DinnerHowe
博客等级 码龄10年 309粉丝 75原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值