Keyword explicit

Keywords can only be used in the class constructor. Its role is not implicit conversion.

 1 class gxgExplicit  //没有关键字explicit的类
 2 
 3 {
 4 
 5 public:
 6 
 7    int _size;
 8 
 9    gxgExplicit(int size)
10 
11    {
12 
13       _size = size;
14 
15    }
16 
17 };

 

Here is the call

gxgExplicit gE1(24);     //这样是没有问题的

   gxgExplicit gE2 = 1;     //这样也是没有问题的

   gxgExplicit gE3;         //这样是不行的,没有默认构造函数

   gE1 = 2;                 //这样也是没有问题的

   gE2 = 3;                 //这样也是没有问题的

   gE2 = gE1;               //这样也是没有问题的

 

 

But if gxgExplicit revised to Stack, our _size represents the size of the stack, the second sentence becomes nondescript calls, and people get confused. This is not to allow the code reader to understand and acceptable form, although it is legal (compiler can compile). This is because the compiler default have implicit conversion function case, you enter gE2 = 1 will compile to the same result with the first sentence. So, explicit came in handy. Modify the code as follows:

 1 class gxgExplicit
 2 
 3 {
 4 
 5 public:
 6 
 7    int _size;
 8 
 9    explicit gxgExplicit(int size)
10 
11    {
12 
13       _size = size;
14 
15    }
16 
17 };

 

Continuing with the above call:

gxgExplicit gE1(24);     //这样是没有问题的

   gxgExplicit gE2 = 1;     //这样是不行的,关键字取消了隐式转换

   gxgExplicit gE3;         //这样是不行的,没有默认构造函数

   gE1 = 2;                 //这样是不行的,关键字取消了隐式转换

   gE2 = 3;                 //这样是不行的,关键字取消了隐式转换

   gE2 = gE1;               //这样是不行的,关键字取消了隐式转换,除非类实现操作符“=”的重载。

 

This is the compiler (vs2005) show: can not convert from 'int' to 'gxgExplicit'.

From here we will see action this keyword is the compiler implicit conversion functions to shield off.

 

Note that there is a point on MSDN fact described below, when more than two constructor parameters implicit conversion is automatically canceled. E.g

 1 class gxgExplicit
 2 
 3 {
 4 
 5 private:
 6 
 7    int _size;
 8 
 9    int _age;
10 
11 public:
12 
13    explicit gxgExplicit(int age, int size)
14 
15    {
16 
17       _age = age;
18 
19       _size = size;
20 
21    }
22 
23 };

 

This is not your keyword performance is the same. That is the equivalent of the keyword.

But another one exception: only one of the parameters to be entered, the remainder being parameters that have default values.

 1 class gxgExplicit
 2 
 3 {
 4 
 5 private:
 6 
 7    int _size;
 8 
 9    int _age;
10 
11 public:
12 
13    explicit gxgExplicit(int age, int size = 0)
14 
15    {
16 
17       _age = age;
18 
19       _size = size;
20 
21    }
22 
23 };

Reproduced in: https: //my.oschina.net/u/204616/blog/545486

Guess you like

Origin blog.csdn.net/weixin_34217711/article/details/91989283