在explicit前首先要了解一个概念:隐式转换
class student{public:student(std::string &name);student(int id);void copy_stu(student &stu);}以上两个构造函数定义了string与int两个隐式转换,因此在期待student对象的地方可以使用一个int或者一个stringstudent 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对象