class Foo{private:int m_foo;
public:// single parameter constructor, can be used as an implicit conversionFoo (int foo) : m_foo (foo) {}
int GetFoo () { return m_foo; }};
/*explicit conversion implicit conversion
explicit constructor yes no
constructor yes yes
explicit conversion function yes no
conversion function yes yes
*/
使用结构X, Y, Z和函数foo, bar, baz的示例:
让我们看一个小的结构和函数设置,看看explicit和非explicit转换之间的区别。
struct Z { };
struct X {explicit X(int a); // X can be constructed from int explicitlyexplicit operator Z (); // X can be converted to Z explicitly};
struct Y{Y(int a); // int can be implicitly converted to Yoperator Z (); // Y can be implicitly converted to Z};
void foo(X x) { }void bar(Y y) { }void baz(Z z) { }
关于构造函数的示例:
函数参数的转换:
foo(2); // error: no implicit conversion int to X possiblefoo(X(2)); // OK: direct initialization: explicit conversionfoo(static_cast<X>(2)); // OK: explicit conversion
bar(2); // OK: implicit conversion via Y(int)bar(Y(2)); // OK: direct initializationbar(static_cast<Y>(2)); // OK: explicit conversion
对象初始化:
X x2 = 2; // error: no implicit conversion int to X possibleX x3(2); // OK: direct initializationX x4 = X(2); // OK: direct initializationX x5 = static_cast<X>(2); // OK: explicit conversion
Y y2 = 2; // OK: implicit conversion via Y(int)Y y3(2); // OK: direct initializationY y4 = Y(2); // OK: direct initializationY y5 = static_cast<Y>(2); // OK: explicit conversion
关于转换函数的示例:
X x1{ 0 };Y y1{ 0 };
函数参数的转换:
baz(x1); // error: X not implicitly convertible to Zbaz(Z(x1)); // OK: explicit initializationbaz(static_cast<Z>(x1)); // OK: explicit conversion
baz(y1); // OK: implicit conversion via Y::operator Z()baz(Z(y1)); // OK: direct initializationbaz(static_cast<Z>(y1)); // OK: explicit conversion
对象初始化:
Z z1 = x1; // error: X not implicitly convertible to ZZ z2(x1); // OK: explicit initializationZ z3 = Z(x1); // OK: explicit initializationZ z4 = static_cast<Z>(x1); // OK: explicit conversion
Z z1 = y1; // OK: implicit conversion via Y::operator Z()Z z2(y1); // OK: direct initializationZ z3 = Z(y1); // OK: direct initializationZ z4 = static_cast<Z>(y1); // OK: explicit conversion