接口的设计(让类被正确的使用)——《Effective c++》

effective c++ 和 more effective c++中知识点 尽可能使用 const在 C++ 编程中,尽可能使用。 阅读详情

要开发一个不容易被误用的类,我们就要首先考虑用你的类的用户可能会犯怎样的错误


//首先介绍一下explicit
//考虑如下代码:
class String {
String ( int n ); //本意是预先分配n个字节给字符串
String ( const char* p ); // 用C风格的字符串p作为初始化值
...
}

String s2 ( 10 );   //OK 分配10个字节的空字符串
String s3 = String ( 10 ); //OK 分配10个字节的空字符串


String s4 = 10; //编译通过,也是分配10个字节的空字符串
String s5 = ‘a’; //编译通过,分配int(‘a’)个字节的空字符串


//s4 和s5 分别把一个int型和char型,隐式转换成了分配若干字节的空字符串,容易令人误解。
//为了避免这种错误的发生,我们可以声明显示的转换,使用explicit 关键字,这样,后面的两个操作将不会被编译通过
//explicit 预防出现隐式转换
struct Day{
    explicit Day(int d) :val(d){};
    int val;
};
struct Month{
    explicit Month(int m) :val(m){};
    int val;
};
struct Year{
    explicit Year(int y) :val(y){};
    int val;
};
class Date{

private:
    Year _year;
    Month _month;
    Day _day;
public:
    Date(const  Month& mon, const  Day& day, const  Year& year) :_year(year), _month(mon), _day(day){};


};
int  main(){

    //  Date d(1,4,5);  //错误
    //  Date d(Month(5),Year(2015),Day(25));  //错误
      Date d(Month(5),Day(25),Year(2015));  //正确
      //防止用户不小心误用
    system("pause");
    return 0;
}

//为了防止用户输入的Date符合标准,比如一年只有十二个月,我们也可以这样设计class Month(其他的如每月的天数同样可以如此)
class Month{
public:
    static Month Jan(){ return Month(1); };
    //...
    explicit Month(int m) :val(m){};
private:
    int val;
};
//然后用户调用接口时,就只能写这样的代码:
Date d(Month::Jan(), Day(25), Year(2015));  //正确
//规范用户的行为,为用户考虑到所有可能犯错的方面
//当然,以上的例子太过于理想化了,但是这个思想是可以借鉴的。就这样
Effective C++ 详解条款18. 让接口容易被正确使用 例子1:导入简单的外覆类型 假如有一个用来表现日期的class设计构造函数: class Date{ public: Date(int month, int day, int year); } 使用者很容易犯下两个错误:1.以错误的次序传递参数。2.传递一个无效的月份或天数。 为了预防这样的问题,可以导入新的类型来获得预防,即导入外覆类型(wrapper types)来区别天数、月份和年份,然后于构造函数中使用这些类型: struct Day{ explicit Day(int d):val(d) 阅读详情

相关推荐

Quartus II 13.0安装避坑指南:从下载到破解的完整流程(附常见错误解决方案)

本文提供Quartus II 13.0软件的详细安装与破解指南,涵盖从下载准备、路径设置、主程序安装到授权配置的全流程。重点解析了破解过程中生成和修改license.dat文件的核心步骤,并针对“无法找到有效的License文件”等常见错误提供了实用的解决方案,帮助用户快速构建稳定的FPGA开发环境。

weixin_29291863的博客 772

正经的c++面向对象技巧——如何方便的只对特定类暴露特定接口

//目标:在AB获得的对象为同一个的时候,只对A暴露imple的todo接口 方法1: 稍显麻烦 class Imple; class AReference { void todo (Imple&); }; class BReference { void todo (Imple&); }; class Imple { //禁止外部获取 ...

qq_39886579的博客 835

OpenCV和Halcon分别实现彩色图像的白平衡效果

实现白平衡算法中的灰度世界法,能有效改善图像发红/发蓝/发绿的现象 1、OpenCV #include <opencv2/opencv.hpp> using namespace cv; int main() { Mat g_srcImage,dstImage; vector<Mat> g_vChannels; g_srcImage = im...

$firecat利白的代码足迹$ 2839

Effective C++学习笔记:争取使类的接口完整并且最小

类的用户接口是指使用这个类的程序员所能访问得到的接口。典型的接口里只有函数存在,因为在用户接口里放上数据成员会有很多缺点。应该把哪些函数放到接口里面呢?原则:接口完整且最小。所谓完整就是使用户能完成所有合理的功能,意即合理的任务有合理的方法。最小就是函数尽量少,两个函数之间没有功能覆盖。函数太多的接口有三点:(1)函数多,类的可读性就越差。难于学习、维护。(2)为系统增加开销。

qinmelody的专栏 579

【AAAI 2025】轻量级特征增强新范式!FCM 模块助力小目标检测,即插即用提升模型泛化能力

本文介绍了AAAI 2025提出的轻量级特征增强新范式FCM模块,它通过显式分离并双向交互语义与空间特征,有效解决了小目标检测中特征信息失配的核心难题。该模块设计精巧,计算开销极低,能够即插即用式地嵌入YOLO等主流检测网络,显著提升模型对小目标的泛化检测能力,尤其适用于遥感、自动驾驶等对计算资源敏感的实际场景。

weixin_29056145的博客 299

springboot 启动方式 装配流程 自定义starter 文件加载顺序 常见设计模式

springboot 启动方式 装配流程 自定义starter 文件加载顺序 常见设计模式

sv 947

Effective C++学习笔记(Part Four:Item 18-25)

第4部分:设计与申明(Designs and Declarations) 本部分主要讲述了类的设计原则以及设计规则,以及成员命令、成员函数设计时,应该注意的一些地方;个人感觉这是设计好一个类必不可少的。

Jackery's Special Column 1237

华为OD机试双机位C卷:采购订单 (Py/Java/C/C++/Js/Go)

华为OD机试双机位C卷 采购订单,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,并提供在线OJ模拟做题。华为OD机试真题【采购订单】

qq_45776114的博客 3552

Effective C++笔记--设计与声明

摘自:《Effetive C++》中文版第三版 1.让接口正确被使用,不易被误用 预测用户会犯什么样的错误 比如一个函数 string toString(int month, int day, int year); 如果在没有审查机制下,用户可能会乱序填写参数、不按规则填写参数。 这里我们可以将日期对象进行封装,让用户规范进行使用: string toSt...

博客 396

【UVM实战】第一章:配置UVM环境(以VCS为例),跑通书上的例子(包括清理中间文件方法、使用DVE查看波形方法、命令执行原理探究)

如何配置UVM的VCS运行环境,运行书本上的例子呢?本节将会为你详细解答!

悟已往之不谏 知来者之可追 8152

matlab处理las点云(1)——las/laz格式解析【2027最新版】

matlab中的las/laz格式解析。博客长期更新,本文最近一次更新时间为:2026年12月3日。

点云侠的博客 8472

Effective C++读书笔记(中)

Effective C++读书笔记(四到六章)

still_wtm的博客 526

Python爬取马蜂窝旅游攻略详细实战指南

马蜂窝是国内非常知名的旅游攻略网站,包含了大量的景点介绍、旅行攻略、游记等信息。爬取马蜂窝的数据对于旅游数据分析、旅游产品推荐等有重要价值。但由于马蜂窝对爬虫有一定的反爬措施,并且页面中大量内容通过JavaScript动态加载,爬虫难度相对较大。本篇博客将带你从零开始,使用Python和相关爬虫技术,逐步实现对马蜂窝旅游攻略内容的高效爬取。并结合实战经验,分析反爬策略,提供科学合理的绕过方案。本文介绍了马蜂窝攻略的结构和抓取难点。演示了静态+动态内容的混合爬取技术。介绍了多线程和异步加速方法。

2201_76125261的博客 592

邻桌同事能监听你的网络吗?一文讲透Wi-Fi、HTTPS与ARP欺骗

在数字化办公和移动互联时代,网络安全早已不只是技术专家的事。当我们连上咖啡馆的Wi-Fi或接入公司局域网时,数据包其实在空气中、线缆中默默流转。理解网络通信的基本原理,如无线信号的广播特性、TCP/IP协议栈的分层协作,以及加密机制的作用边界,是建立安全意识的第一步。局域网通信依赖ARP协议进行地址解析,这种信任机制恰恰可能被利用,演变成中间人攻击的入口。而HTTPS/TLS协议通过证书体系和会话密钥加密,能有效保护传输内容的机密性,却也无法完全隐藏域名、流量大小等元数据。从个人防护到企业内网管控,从被动侦

weixin_33770878的博客 228

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

visio安装包

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

《effective C++》读书笔记 2011.3.2

<br />1.    关于条款11:在operator=中处理自我赋值<br />“自我赋值”发生在对象被赋值给自己时,可能会掉进“在停止使用资源之前意外释放它”的陷阱:<br />class Bitmap { … };<br />class Widget {<br />   …<br />private:<br />    Bitmap *pb;    //指针,指向一个从heap分配而得的对象<br />};<br />下面是operator=实现代码:<br />Widget&<br />Widge

412

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

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

Effective C++阅读笔记

Effective C++ 1、让自己习惯C++ 1、C++是四个语言组成的,每个语言有自己的规则。(四种语言:Plain C(面向过程)、OOP(面向对象)、模板(泛型和模板元编程)、STL(C++标准库)) 2、尽量以inline、enum、const代替#define。 3、灵活使用const前缀。不需要进行改变的数据加上const前缀。指针的const前缀有两种形式,const放在*左边表示数据不变,放右边表示指针地址不变。返回不需要修改的成员数据的成员函数需要加上const标记。(成员函数+con

qq_45786156的博客 274

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

Effective C++学习笔记(18)

第七章杂项    条款45: 弄清C++在幕后为你所写、所调用的函数    ---- 一个类当C++编译器通过它的时候。如果你没有声明下列函数,体贴的编译器会声明它自己的版本。这些函数是:一个拷贝构造函数,一个赋值运算符,一个析构函数,一对取址运算符。另外,如果你没有声明任何构造函数,它也将为你声明一个缺省构造函数。class Empty{};      | 等价于      Vclass Emp

468

Effective C++学习笔记

Effective C++》读书笔记Effective Cpp 第三版学习笔记。

weixin_42650596的博客 661

Effective C++学习笔记(3)

条款9: 避免隐藏标准形式的new    条款10: 如果写了operator new就要同时写operator delete缺省的operator new和operator delete具有非常好的通用性,它的这种灵活性也使得在某些特定的场合下,可以进一步改善它的性能。尤其在那些需要动态分配大量的但很小的对象的应用程序里缺省版本的operator new是一种通用型的内存分配器,在它所返回的内存

415

《effective C++》读书笔记 2011.3.1

<br />1.    关于条款4:确定对象被使用前已先被初始化<br />不同编译单元内定义之non-local static对象的初始化次序:<br />static对象,其寿命从被构造出来直到程序结束为止,这种对象包括global对象,定义于namespace作用域内的对象,在classes内,在函数内,以及在file作用域内被声明为static的对象。函数内的static对象称为local static对象(因为他们对函数而言是local),其他static对象称为non-local static对

385

Effective C++核心准则解析:从语言联邦到RAII资源管理

C++作为一门多范式编程语言,其核心设计理念在于通过类型系统、对象生命周期管理和资源获取即初始化(RAII)等机制,构建高效、安全的软件系统。理解C++的四个次语言联邦(C、面向对象C++、模板C++、STL)是掌握其多范式本质的关键,这决定了在不同编程场景下应遵循的最佳实践。const关键字不仅提供编译期常量,更通过成员函数常量性、指针与迭代器修饰等方式,在接口设计中强化契约,提升代码健壮性。资源管理方面,智能指针(如unique_ptr、shared_ptr)和RAII模式将资源生命周期与对象绑定,从根

weixin_30899023的博客 219

[Effective C++]条款18 设计正确易用的接口

C++在接口之海漂浮, 一个好的接口很容易被正确使用, 不容易被误用.条款18其实是一个很宏观的条款, 让接口变得正确易用, 简单来说就是"促进正确使用"和"阻止误用".

tianmu_sama的博客 1954

《Effective C++》《设计与声明——18、让接口容易被正确使用,不易被误用》

18、让接口容易被正确使用,不易被误用

zwh1298454060的博客 1466

【effective c++】条款十八:让接口容易被正确使用,不易被误用

摘要: Effective C++条款18强调设计接口时应使其易于正确使用且难以误用。关键策略包括:1) 促进正确使用:保持接口一致性(如STL的.size()),兼容内置类型行为;2) 防止误用:通过建立包装类型(如Month/Day)、限制操作(const返回值)、约束取值范围(静态工厂函数)等利用类型系统捕获错误;3) 资源管理:使用智能指针(如shared_ptr)转移责任,支持定制删除器解决跨DLL释放和互斥锁管理。现代C++的enum class、explicit和概念(Concepts)进一步

maybe_Tian_Xia的博客 742

Effective C++条款18:让接口容易被正确使用,不容易被误用

Effective C++条款18:让接口容易被正确使用,不容易被误用(Make interfaces easy to use correctly and hard to use incorrectly)

CltCj的博客 920
上一篇: 对引用的一些测试和学习
下一篇: 变长参数函数的实现及原理
codedoctor
博客等级 码龄11年 293粉丝 71原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址