explicit CImg(const char *const filename):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) {
assign(filename);
}
有或没有它的区别是什么?
答案 0 :(得分:7)
用于装饰构造函数;如此修饰的构造函数不能被编译器用于隐式转换。
C ++允许最多一个用户提供的转换,其中“用户提供”表示“通过类构造函数”,例如:
class circle {
circle( const int r ) ;
}
circle c = 3 ; // implicit conversion using ctor
编译器将在此处调用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
答案 1 :(得分: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)
如果没有explicit
关键字,语句(1)和(3)将被编译,因为编译器可以看到const char*
可以隐式转换为CImg
(通过构造函数接受)一个const char*
)。有时这种隐式转换是不可取的,因为它并不总是有意义的。