class A {
public:
A(); // default constructor
};
class B {
public:
explicit B(int x = 0, bool b = true); // default constructor; see below
}; // for info on "explicit"
class C {
public:
explicit C(int x); // not a default constructor
};
The constructors for classes B and C are declared explicit here. That prevents them from being used to perform implicit type conversions, though they may still be used for explicit type conversions:
void doSomething(B bObject); // a function taking an object of
// type B
B bObj1; // an object of type B
doSomething(bObj1); // fine, passes a B to doSomething
B bObj2(28); // fine, creates a B from the int 28
// (the bool defaults to true)
doSomething(28); // error! doSomething takes a B,
// not an int, and there is no
// implicit conversion from int to B
doSomething(B(28)); // fine, uses the B constructor to
// explicitly convert (i.e., cast) the
// int to a B for this call. (See
// Item 27 for info on casting.)
Constructors declared explicit are usually preferable to non-explicit ones, because they prevent compilers from performing unexpected (often unintended) type conversions. Unless I have a good reason for allowing a constructor to be used for implicit type conversions, I declare it explicit. I encourage you to follow the same policy.
博客介绍了类B和C的构造函数显式声明的情况,显式声明可防止编译器执行意外的类型转换,虽仍可用于显式类型转换。通常显式声明的构造函数更优,建议在无特殊理由时都进行显式声明。
728

被折叠的 条评论
为什么被折叠?



