c ++中的显式关键字是什么?

use*_*729 7 c++ syntax

可能重复:
C++中的explicit关键字是什么意思?

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

有或没有它的区别是什么?

tpd*_*pdi 7

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

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

 class circle {
   circle( const int r ) ;
 }

  circle c = 3 ; // implicit conversion using ctor
Run Code Online (Sandbox Code Playgroud)

编译器将在这里调用circle ctor,构造c值为3的循环r.

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

 class circle {
   explicit circle( const int r ) ;
 }

  // circle c = 3 ; implicit conversion not available now
  circle c(3); // explicit and allowed
Run Code Online (Sandbox Code Playgroud)


In *_*ico 5

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)
Run Code Online (Sandbox Code Playgroud)

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