【问题标题】:What is the explicit keyword for in c++? [duplicate]c++中的显式关键字是什么? [复制]
【发布时间】:2011-03-17 13:53:49
【问题描述】:

可能重复:
What does the explicit keyword in C++ mean?

explicit CImg(const char *const filename):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) {
  assign(filename);
}

有没有有什么区别?

【问题讨论】:

标签: c++ syntax


【解决方案1】:

explicit 关键字可防止隐式转换。

// Does not compile - an implicit conversion from const char* to CImg
CImg image = "C:/file.jpg"; // (1)
// Does compile
CImg image("C:/file.jpg"); // (2)

void PrintImage(const CImg& img) { };

PrintImage("C:/file.jpg"); // Does not compile (3)
PrintImage(CImg("C:/file.jpg")); // Does compile (4)

如果没有 explicit 关键字,语句 (1) 和 (3) 将编译,因为编译器可以看到 const char* 可以隐式转换为 CImg(通过接受 const char* 的构造函数)。有时这种隐式转换是不可取的,因为它并不总是有意义。

【讨论】:

    【解决方案2】:

    用于装饰构造函数;编译器不能将如此修饰的构造函数用于隐式转换。

    C++ 最多允许一次用户提供的转换,其中“用户提供”表示“通过类构造函数”,例如:

     class circle {
       circle( const int r ) ;
     }
    
      circle c = 3 ; // implicit conversion using ctor
    

    编译器将在此处调用圆 ctor,构造圆 cr 的值为 3。

    explicit 在你不想要这个时使用。添加显式意味着您必须显式构造:

     class circle {
       explicit circle( const int r ) ;
     }
    
      // circle c = 3 ; implicit conversion not available now
      circle c(3); // explicit and allowed
    

    【讨论】:

      猜你喜欢
      • 2019-04-23
      • 2020-10-11
      • 2013-08-14
      • 2011-08-17
      • 2012-09-29
      • 2010-09-12
      • 2012-07-01
      • 1970-01-01
      相关资源
      最近更新 更多