【发布时间】:2011-03-17 13:53:49
【问题描述】:
explicit CImg(const char *const filename):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) {
assign(filename);
}
有没有有什么区别?
【问题讨论】:
explicit CImg(const char *const filename):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) {
assign(filename);
}
有没有有什么区别?
【问题讨论】:
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* 的构造函数)。有时这种隐式转换是不可取的,因为它并不总是有意义。
【讨论】:
用于装饰构造函数;编译器不能将如此修饰的构造函数用于隐式转换。
C++ 最多允许一次用户提供的转换,其中“用户提供”表示“通过类构造函数”,例如:
class circle {
circle( const int r ) ;
}
circle c = 3 ; // implicit conversion using ctor
编译器将在此处调用圆 ctor,构造圆 c,r 的值为 3。
explicit 在你不想要这个时使用。添加显式意味着您必须显式构造:
class circle {
explicit circle( const int r ) ;
}
// circle c = 3 ; implicit conversion not available now
circle c(3); // explicit and allowed
【讨论】: