C++之explicit关键字

C++中explicit关键字是用来声明类构造函数的显示调用,默认情况下是类的构造函数是隐式调用的。无参构造函数和多参构造函数本身就是显示调用的,因此explicit只用于修饰单参构造函数。

#include<cstring>
#include<string>
#include<iostream>
using namespace std;

class Explicit
{
private:
    int _size;
    string _str;
public:
    Explicit(int size)
    {
        _size = size;
        cout << " size is " << size << endl;
    }
    Explicit(const char* str)
    {
        _str = str;
        cout << " str is " << _str << endl;
    }
    Explicit(const Explicit& ins)
    {
        _size = ins._size;
        cout << " Explicit is ins,size is " << _size << endl;
    }
};

int main()
{
    Explicit test1_1(10);
    Explicit test1_2 = 20;//隐式调用Explicit(int size)

    Explicit test2_1("explicit call");
    Explicit test2_2 = "implicit call";//隐式调用Explicit(const char* str)

    Explicit test3_1= test1_1;//隐式调用Explicit(const Explicit& ins)
    Explicit test3_2 = test1_2;//隐式调用Explicit(const Explicit& ins)

    return 0;
}

上述代码“Explicit test1_2 = 20”为什么可以编译通过呢?那是因为在C++中, 如果类的构造函数只有一个参数时,那么在编译的时候就会有一个缺省的转换操作,即将该构造函数对应数据类型的数据转换为该类对象,代码“Explicit test1_2 = 20”也就等同于代码“Explicit test1_2(20)”。上面的程序虽然没有错误,但是对于Explicit test1_2 = 20和Explicit test2_2 = "implicit call"这样的代码,把一个int类型或者const char*类型的变量赋值给Explicit类型的变量看起来总归不是很好,并且当程序很大的时候出错之后也不容易排查。所以为了禁止上面那种隐式转换可能带来的风险,一般都把类的单参构造函数声明的显示调用的,就是在构造函数加关键字explicit

#include<cstring>
#include<string>
#include<iostream>
using namespace std;

class Explicit
{
private:
    int _size;
    string _str;
public:
    explicit Explicit(int size)
    {
        _size = size;
        cout << " size is " << size << endl;
    }
    explicit Explicit(const char* str)
    {
        _str = str;
        cout << " str is " << _str << endl;
    }
    explicit Explicit(const Explicit& ins)
    {
        _size = ins._size;
        cout << " Explicit is ins,size is " << _size << endl;
    }
};

int main()
{
    Explicit test1_1(10);
    //Explicit test1_2 = 20;//不允许隐式调用Explicit(int size),编译器报错,没有适当的构造函数

    Explicit test2_1("explicit call");
    //Explicit test2_2 = "implicit call";//不允许隐式调用Explicit(const char* str),编译器报错,没有适当的构造函数

    //Explicit test3_1= test1_1;// 不允许隐式调用Explicit(const Explicit& ins),编译器报错,没有适当的构造函数
    //Explicit test3_2 = test1_2;// 不允许隐式调用Explicit(const Explicit& ins),编译器报错,没有适当的构造函数

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值