C++核心準(zhǔn)則C.52:合理使用繼承的構(gòu)造函數(shù)

C.52:使用繼承的構(gòu)造函數(shù)功能將構(gòu)造函數(shù)導(dǎo)入不再需要進(jìn)一步明確初始化的派生類(lèi)
If you need those constructors for a derived class, re-implementing them is tedious and error-prone.
如果派生類(lèi)需要那些構(gòu)造函數(shù),重新實(shí)現(xiàn)它們的工作單調(diào)乏味而且容易發(fā)生錯(cuò)誤。
std::vector has a lot of tricky constructors, so if I want my own vector, I don't want to reimplement them:
std::vector有大量的構(gòu)造函數(shù)很難用,因此如果我需要自己的vector,我不會(huì)重新實(shí)現(xiàn)它們。
class Rec {
? ?// ... data and lots of nice constructors ...
};
class Oper : public Rec {
? ?using Rec::Rec;
? ?// ... no data members ...
? ?// ... lots of nice utility functions ...
};struct Rec2 : public Rec {
? ?int x;
? ?using Rec::Rec;
};
Rec2 r {"foo", 7};
int val = r.x; ? // uninitialized
這就是需要進(jìn)一步初始化的例子。如果派生類(lèi)沒(méi)有增加數(shù)據(jù)成員只是增加一些功能,就可以使用using Rec::Rec這種方法導(dǎo)入基類(lèi)的構(gòu)造函數(shù)。對(duì)于上面的例子也可以考慮使用類(lèi)內(nèi)初始化器初始化數(shù)據(jù)成員x。

Make sure that every member of the derived class is initialized.
保證派生類(lèi)的所有成員都被初始化。
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
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎迹?/span>
