explicit

explicit前首先要了解一个概念:隐式转换

class student
{
public:
     student(std::string &name);
     student(int id);
     void copy_stu(student &stu);
}
以上两个构造函数定义了string与int两个隐式转换,因此在期待student对象的地方可以使用一个int或者一个string
     student zs("张三");
     zs.copy_stu(std::string("李四"));//李四隐式转为student对象在传递给函数
     zs.copy_stu(2009211);//2009211隐式转为student对象

explicit可以 抑制由构造函数定义的隐式转换
class student
{
public:
     explicit student(std::string &name);
     explicit student(int id);
     void copy_stu(student &stu);
}
explicit 关键字只能用于类内部的构造函数声明上。不用在类的定义体外部所做的 定义上重复它。

      student zs("张三");
     zs.copy_stu(std::string("李四"));// error:由于声明了explicit不能再隐式创建student对象
     zs.copy_stu(student(std::string("李四")));// OK:显示的转换为student对象
     zs.copy_stu(2009211);// error: 由于声明了explicit不能再隐式创建student对象
     zs.copy_stu(student(2009211));// OK:显示的转换为student对象
     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值