码迷,mamicode.com
首页 > 其他好文 > 详细

explicit运算符

时间:2017-10-14 19:59:50      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:note   数据   pretty   转换   tor   str   构造   size   hat   

  引用StackOverFlow中的例子:

struct Foo {
  int value; // Foo stores an int, called value
  Foo(int v):value(v) {}; // Foo can be constructed (created) from an int
  explicit Foo(double d):value(d) {}; // Foo can be constructed (created) from a double
  // ^^^ note that keyword.  It says that it can only be EXPLICITLY created from a double
};


按照规定,只有一个参数的构造函数也定义了一个隐式转换,将该构造函数对应数据类型的数据转换为该类对象
在此构造函数前加了explicit后,用来抑制隐式转换
explicit只对构造函数起作用

Foo i = 0.0;

This fails to compile. I said that the constructor for Foo(double) is explicit, and the above only chooses to call constructors that are non-explicit. On the other hand:


Foo i(0.0);
Foo i = Foo(0.0);

these both are willing to call explicit constructors, and work fine.


 

explicit运算符

标签:note   数据   pretty   转换   tor   str   构造   size   hat   

原文地址:http://www.cnblogs.com/yzz0110/p/7668032.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!