C++核心准则C.51:使用委托构造函数实现所有构造函数的共通动作
发布日期:2021-07-01 05:26:36 浏览次数:3 分类:技术文章

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

C.51: Use delegating constructors to represent common actions for all constructors of a class

C.51:使用委托构造函数实现所有构造函数的共通动作

 

委托构造函数是C++11引入的新特性,具体请参照作者的以下文章:

https://mp.weixin.qq.com/s/sHyLCI1tkLWvxfBKUiKwMg

 

Reason(原因)

To avoid repetition and accidental differences.

避免重复和意外的差异。

 

Example, bad(反面示例)

 

class Date {   // BAD: repetitive    int d;    Month m;    int y;public:    Date(int dd, Month mm, year yy)        :d{dd}, m{mm}, y{yy}        { if (!valid(d, m, y)) throw Bad_date{}; }    Date(int dd, Month mm)        :d{dd}, m{mm} y{current_year()}        { if (!valid(d, m, y)) throw Bad_date{}; }    // ...};

 

The common action gets tedious to write and may accidentally not be common.

共通的动作写起来很乏味,偶尔也会变得不普通。

 

 

Example(示例)

 

class Date2 {    int d;    Month m;    int y;public:    Date2(int dd, Month mm, year yy)        :d{dd}, m{mm}, y{yy}        { if (!valid(d, m, y)) throw Bad_date{}; }    Date2(int dd, Month mm)        :Date2{dd, mm, current_year()} {}    // ...};

 

See also: If the "repeated action" is a simple initialization, consider an in-class member initializer.

参考:如果“重复的动作”只是简单的初始化,考虑类内成员初始化器。

 

Enforcement(实施建议)

(Moderate) Look for similar constructor bodies.

(中等)寻找函数体相似的构造函数。

 

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c51-use-delegating-constructors-to-represent-common-actions-for-all-constructors-of-a-class

 


 

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

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

转载地址:https://oothinking.blog.csdn.net/article/details/104596994 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:C++核心准则C.52:合理使用继承的构造函数
下一篇:C++核心准则C.50:如果在构造过程中需要“虚行为”,使用工厂函数

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月24日 10时07分40秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章