当前位置:编程学习 > C/C++ >>

C++ 之explicit用法

 

explicit

C++   Specific  

 

This   keyword   is   a   declaration   specifier   that   can   only   be   applied   to   in-class   constructor   declarations.   Constructors   declared   explicit   will   not   be   considered   for   implicit   conversions.   For   example:

 

class   X   {

public:

      explicit   X(int);             //legal

      explicit   X(double)   {       //legal

            //   ...

      }

};

 

explicit   X::X(int)   {}             //illegal

An   explicit   constructor   cannot   take   part   in   implicit   conversions.   It   can   only   be   used   to   explicitly   construct   an   object.   For   example,   with   the   class   declared   above:

 

void   f(X)   {}

void   g(int   I)   {

      f(i);             //   will   cause   error

}

void   h()   {

      X   x1(1);             //   legal

}

The   function   call   f(i)   fails   because   there   is   no   available   implicit   conversion   from   int   to   X.

 

Note       It   is   meaningless   to   apply   explicit   to   constructors   with   multiple   arguments,   since   such   constructors   cannot   take   part   in   implicit   conversions.

 

END   C++   Specific

 

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,