关键字explicit

构造函数被声明为explicit,可以阻止他们被用来执行隐式类型转换,但他们仍可以被用来进行显式类型转换

explicit的构造函数禁止编译器执行非预期的类型转换。


以下来自MSDN:

This keyword is a declaration specifier that can only be applied to in-class constructor declarations. An explicit constructor cannot take part in implicit conversions. It can only be used to explicitly construct an object.


The following program will fail to compile because of the explicit keyword. To resolve the error, remove the explicit keywords and adjust the code in g.

// spec1_explicit.cpp
// compile with: /EHsc
#include <stdio.h>

class C 
{
public:
    int i;
    explicit C(const C&)   // an explicit copy constructor
    {
        printf_s("\nin the copy constructor");
    }
    explicit C(int i )   // an explicit constructor
    {
        printf_s("\nin the constructor");
    }

    C()
    {
        i = 0;
    }
};

class C2
{
public:
    int i;
    explicit C2(int i )   // an explicit constructor
    {
    } 
};

C f(C c)
{   // C2558
    c.i = 2;
    return c;   // first call to copy constructor
}

void f2(C2)
{
}

void g(int i)
{
    f2(i);   // C2558
    // try the following line instead
    // f2(C2(i));
}

int main()
{
    C c, d;
    d = f(c);   // c is copied
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值