c++_explicit的作用

在C++中,explicit关键字主要用于防止隐式转换(避免构造函数的参数自动转换为类对象的标识符),用于修饰构造函数、复制构造函数。

#include <iostream>
 
using namespace std;
 
class Test{
public:
    Test(int i)
    {
        cout<<"构造函数"<<endl;
    }
 
  int data;
};
 
int main(int argc, char *argv[])
{
    Test a = 10;
 
    return 0;
}

例如上述代码:

    首先Test a = 0这种写法肯定是错误的,可是编译器呢通过搜索发现A类对象构造函数可以通过int来构造,而且

Test(int i)并没有被explicit修饰,所以Test a = 0会为0生成一个对象,然后将对象赋值给a
 
假如我们稍作改动假如explicit修饰,如下
#include <iostream>
using namespace std;
class Test{
public:
    explicit Test(int i)
    {
        cout<<"con"<<endl;
    }
  int data;
};
int main(int argc, char *argv[])
{
    Test a = 10;
    return 0;
}
编译报错
	如下
	C:\Users\Administrator\Desktop\c++_test\explict\main.cpp:17: error: conversion from 'int' to non-scalar type 'Test' requested
     Test a = 10;
              ^
	加入explicit后a = 10相当于a.operator = (10),a对象怎么会等于10呢?所以便报错了
 
 
 
 
 
 
 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值