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

网友投稿 581 2022-10-25

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

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

C.51: Use delegating constructors to represent common actions for all constructors of a class C.51:使用委托构造函数实现所有构造函数的共通动作

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

​​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.

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:基于Kotlin利用Coroutines+Okhttp3+Retrofit的网络框架
下一篇:Laravel 框架前后端模块化开发实践
相关文章

 发表评论

暂时没有评论,来抢沙发吧~