c++ vector 初始化_C++核心准则C.52:合理使用继承的构造函数功能

本文介绍了C++中使用继承构造函数来避免在派生类中重复实现基类的构造函数,从而减少错误和提高代码效率。示例展示了如何通过`using基类::基类;`来导入基类的构造函数,并强调了确保派生类所有成员都被初始化的重要性。
摘要由CSDN通过智能技术生成
9b9f9dba9cff699bd759deeb0249292f.png

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这种方法导入基类的构造函数。

Enforcement(实施建议)

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

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

原文链接

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


觉得本文有帮助?请分享给更多人。

更多精彩文章请关注微信公众号【面向对象思考】!

面向对象开发,面向对象思考!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值