博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++核心准则C.52:合理使用继承的构造函数
阅读量:2016 次
发布时间:2019-04-28

本文共 1251 字,大约阅读时间需要 4 分钟。

C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization

C.52:使用继承的构造函数功能将构造函数导入不再需要进一步明确初始化的派生类

 

Reason(原因)

If you need those constructors for a derived class, re-implementing them is tedious and error-prone.

如果派生类需要那些构造函数,重新实现它们的工作单调乏味而且容易发生错误。

 

Example(示例)

std::vector has a lot of tricky constructors, so if I want my own vector, I don't want to reimplement them:

std::vector有大量的构造函数很难用,因此如果我需要自己的vector,我不会重新实现它们。

 

class Rec {    // ... data and lots of nice constructors ...};class Oper : public Rec {    using Rec::Rec;    // ... no data members ...    // ... lots of nice utility functions ...};

 

 

Example, bad(反面示例)

 

struct Rec2 : public Rec {    int x;    using Rec::Rec;};Rec2 r {"foo", 7};int val = r.x;   // uninitialized

 

 

这就是需要进一步初始化的例子。如果派生类没有增加数据成员只是增加一些功能,就可以使用using Rec::Rec这种方法导入基类的构造函数。对于上面的例子也可以考虑使用类内初始化器初始化数据成员x。

 

 

Enforcement

Make sure that every member of the derived class is initialized.

保证派生类的所有成员都被初始化。

 

 

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c52-use-inheriting-constructors-to-import-constructors-into-a-derived-class-that-does-not-need-further-explicit-initialization

 


 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

转载地址:http://eyixf.baihongyu.com/

你可能感兴趣的文章
Android入门笔记16: EditText 和 返回键
查看>>
909422229_Jeesite多表联合列表分页实现
查看>>
909422229_阻塞与非阻塞的区别
查看>>
Node.js学习 - GET/POST
查看>>
CentOS7安装Nginx并部署
查看>>
Zookeeper安装使用及JavaAPI使用
查看>>
SQL Server中的数据类型
查看>>
SpringMVC学习系列(4) 之 数据绑定-1
查看>>
秒杀的基本知识点,了解一下
查看>>
微服务之间的最佳调用方式,你会了吗
查看>>
Linux如何在系统启动时自动加载模块
查看>>
链路层到网络层的数据传递
查看>>
vxworks
查看>>
软件测试用例的基本要素
查看>>
关于sprintf的一些东西(在stdio.h里)
查看>>
八皇后的思考(DFS)
查看>>
机器学习:SVM(基础理解)
查看>>
机器学习:SVM(SVM 思想解决回归问题)
查看>>
Hbase学习笔记(一)
查看>>
Hbase学习笔记(三)
查看>>