C++核心準則C.52:合理使用繼承的構造函數

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

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章