C++ 抑制构造函数定义的隐式转换

本文通过一个具体的C++类实例,详细介绍了如何使用explicit关键字来限制构造函数的使用方式,防止不必要的类型隐式转换,特别是在使用初始化列表时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:《C++ Primer》 P256

构造函数添加explicit关键字修饰

例子

class StrBlob{
public:
    typedef std::vector<std::string>::size_type size_type;
    StrBlob();

    //StrBlob(std::initializer_list<std::string> il);
    explicit StrBlob(std::initializer_list<std::string> il);

    size_type size() const{ return data->size(); }
    bool empty() const{ return data->empty(); }

    void push_back(const std::string &str){ data->push_back(str); }
    void pop_back();
    std::string & front();
    /*
    如果定义const StrBlob 对象,则front函数应该对const进行重载,因为如果不重载,则const StrBlob 常量对象的this指针,
    不能传给函数front的非常量的this指针,从而无法访问data数据成员,同时返回的元素类型也应该是const,因为const StrBlob 为常量对象
    */
    const std::string & front() const; 
    std::string & back();
    const std::string &back() const;

private:
    std::shared_ptr<std::vector<std::string>> data;
    void check(size_type i, const std::string &msg) const;
};


StrBlob b1;
    for (size_t i = 0; i < 1; i++)
    {
        //StrBlob b2 = StrBlob({"a", "an", "the" });
        StrBlob b2 = { "a", "an", "the" };
        cout << b2.size()<<endl;
        b1 = b2;
        b2.push_back("about");
    }
    cout << b1.size() << endl;

当使用构造函数StrBlob(std::initializer_list il)时,初始化StrBlob的对象既可以执行直接初始化:StrBlob b2{ “a”, “an”, “the” };又可以执行拷贝形式的初始化:StrBlob b2 = { “a”, “an”, “the” };

当使用构造函数explicit StrBlob(std::initializer_list il)时,只能执行直接初始化:StrBlob b2{ “a”, “an”, “the” },因为explicit作用,初始化列表类型{ “a”, “an”, “the” }不能隐式转换为StrBlob类型; 但是可以StrBlob b2 = StrBlob({“a”, “an”, “the” })初始化;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值