C++笔记(一)explicit

来源:互联网 发布:315曝光的淘宝代购店铺 编辑:程序博客网 时间:2024/04/27 23:55

关键字explicit,用于构造函数,可以阻止构造函数的隐式转换,构造函数声明explicit后如果使用隐式转换会报错。

隐式转换:例

class Person

{

public:

Person(int age);

......

}

......

Person Tom = 20;//调用隐式转换,等同于

//Person temp(20);

//Person Tom = temp;

有的时候不需要隐式转换,或者隐式转换会带来一些意想不到的问题:

class Person

{

public:

Person(int age);

Person(const char* name);

......

}

......

Person tom = 20;//tom的年龄为20

Person tom = "tom";//tom的名字为tom

Person lucy = 'a';//lucy的年龄为int('a')=97

这三条语句都编译通过了,但是lucy的年龄为97岁并不是我们想要的

如果在两个构造函数的前面都加上explicit修饰后,再执行上述代码就会出现编译错误,cannot convery form 类型 to class Person

explicit Person(int age);

explicit Person(const char* name);



原创粉丝点击