explicit 只对有一个参数(或者有多个参数,但除了第一个,其他参数都有默认值)的构造函数起作用。explicit针对的是其他类型在向某class转换时必须遵循构造函数的参数类型,而构造函数的参数类型则可以进行implicit转换。两者对应的层次不同。
google的style guide里写道:
We require all single argument constructors to be explicit. Always put explicit in front of one-argument constructors in the class definition: explicit Foo(string name);
The exception is copy constructors, which, in the rare cases when we allow them, should probably not be explicit. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments.
cppreference的例子很好:
struct foo {
explicit foo( int a )
: a_( a )
{ }
int a_;
};
int bar( const foo & f ) {
return f.a_;
}
bar( 1 ); // fails because an implicit conversion from int to foo
// is forbidden by explicit.
bar( foo( 1 ) ); // works -- explicit call to explicit constructor.
bar( static_cast
bar( foo( 1.0 ) ); // works -- explicit call to explicit constructor
// with automatic conversion from float to int.

没有评论:
发表评论