explicit constructor(显示构造函数)

时间:2023-03-09 17:20:14
explicit constructor(显示构造函数)

按照默认规定,只有一个参数的构造函数也定义了一个隐式转换,将该构造函数对应的数据类型的数据转换为该类对象,如下所示:

  1. class String
  2. {
  3. String(const char* p) //用C风格的字符串p作为初始值
  4. //........
  5. }
  6. String s1 = "hello"; //OK,隐式转换,等价于String s1 = String('hello')

但是有的时候可能会不需要这种隐式转换,如下:

  1. class String
  2. {
  3. String(int n) //本意是预先分配n个字节给字符串
  4. String(const char* p); //用C风格的字符串p作为初始值
  5. //........
  6. }

下面的两种写法是正常的:

  1. String s2(10); //OK,即分配10个字节的空字符串
  2. String s3 = String (10); //OK,即分配10个字节的空字符串

但是以下的两种写法会使我们感到疑惑:

  1. String s4 = 10;  //编译通过,即分配了10个字节的空字符串
  2. String s5 = 'a'; //编译通过,分配int('a')个字节的空字符串

s4和s5分别是把一个int型和char型,隐式转换成了分配若干个字节的空字符串,容易令人误解。

为了避免这种错误的发生,我们可以声明显示的转换,即使用explicit关键字:

  1. class String
  2. {
  3. <span style="color:#cc0000;">explicit</span> String(int n) //本意是预先分配n个字节给字符串
  4. String(const char* p); //用C风格的字符串p作为初始值
  5. //........
  6. }

加上explicit,就抑制了String(int n)的隐式转换

即下面的两种写法仍然是正确的:

  1. String s2(10); //OK,即分配10个字节的空字符串
  2. String s3 = String (10); //OK,即分配10个字节的空字符串

但是先前的两种写法就编译不能通过了,例如:

  1. String s4 = 10;  //编译不通过,不允许隐式转换
  2. String s5 = 'a'; //编译不通过,不允许隐式转换

因此某些时候,explicit可以有效地防止构造函数的隐式转换带来的错误或者误解。

举例进一步阐释:

explicit只对构造函数起作用,用来抑制隐式转换,如下:

  1. class A
  2. {
  3. A(int a);
  4. };
  5. int Function(A a);

当调用Function(2)的时候,会隐式转换为A类型。这种情况常常不是我们所想要的结果,所以,要避免这种情形,我们就可以这样写:

  1. class A
  2. {
  3. explicit A(int a);
  4. };
  5. int Function(A a);

这样,当调用Function(2)的时候,编译器会给出错误的信息(除非Function有个以int为参数的重载形式),这就避免了在我们毫不知情的情况下出现的错误。