探究隐式转换 explicit

《Effective C++》 导读

探究隐式转换 explicit
explicit:
通过将 ctor 声明为explicit,可以阻止它们被用来执行隐式转换(implicit type conveesions),
但是它们仍可被用来进行显示类型转换

#include <iostream>

class A{
public:
    A(){
        std::cout << "ctor A()" << std::endl;
    }
};

class B{
public:
    explicit B( int x = 0, bool b = true ){
        std::cout << "ctor B()" << std::endl;
    }

public:
    int x;
    bool b;
};

class C{
public:
    explicit C( int x ){
        std::cout << "ctor C()" << std::endl;
    }

public:
    int x;
};

void DoSomething( B obj ){
    std::cout << "func() DoSomething" << std::endl;
}

int main( ){
    B b_obj_1;                  // 可以
    DoSomething( b_obj_1 );     //可以
    B b_obj_2(28);              // 可以,(此时 b参数缺省为 true)

    // DoSomething( 28 );          // 禁止隐式转换了
    DoSomething( B(28) );       // 可以~

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值