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

 

 http://hi.baidu.com/qiangsoft/blog/item/ef67a6835bd35eb56d811934.html

explicit

  C++提供了关键字explicit,可以阻止不应该允许的经过转换构造函数进行的隐式转换的发生。声明为explicit的构造函数不能在隐式转换中使用。
  C++中, 一个参数的构造函数, 承担了两个角色。 1 是个构造器 2 是个默认且隐含的类型转换操作符。
  所以, 有时候在我们写下如 AAA = XXX, 这样的代码, 且恰好XXX的类型正好是AAA单参数构造器的参数类型, 这时候编译器就自动调用这个构造器, 创建一个AAA的对象。
  这样看起来好象很酷, 很方便。 但在某些情况下(见下面权威的例子), 却违背了我们(程序员)的本意。 真是成也萧何, 败也萧何。 这时候就要在这个构造器前面加上explicit修饰, 指定这个构造器只能被明确的调用,使用, 不能作为类型转换操作符被隐含的使用。 呵呵, 看来还是光明正大些比较好。
  explicit构造函数的作用
  解析:
  explicit构造函数是用来防止隐式转换的。请看下面的代码:
  1 class Test1
  2 {
  3 public:
  4 Test1(int n) { num = n; } //普通构造函数
  5 private:
  6 int num;
  7 };
  8
  9 class Test2
  10 {
  11 public:
  12 explicit Test2(int n) { num = n; } //explicit(显式)构造函数
  13 private:
  14 int num;
  15 };
  16
  17 int main()
  18 {
  19 Test1 t1 = 12; //隐式调用其构造函数, 成功
  20 Test2 t2 = 12; //编译错误,不能隐式调用其构造函数
  21 Test2 t3(12); //显示调用成功
  22 return 0;
  23 }
  Test1的构造函数带一个int型的参数,代码19行会隐式转换成调用Test1的这个构造函数。而Test2的构造函数被声明为explicit(显式),这表示不能通过隐式转换来调用这个构造函数,因此代码20行会出现编译错误。
  普通构造函数能够被隐式调用。而explicit构造函数只能被显示调用。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值