Converting constructor
转换构造函数
未用说明符声明的构造函数。显式并且可以用单个参数%28调用,直到C++11%29被称为转换构造函数
...
与显式构造函数不同的是,该构造函数仅在直接初始化%28,其中包括显式转换如静态[医]铸造%29,转换构造函数在复制初始化,作为用户定义的转换序列...
据说,转换构造函数指定从其参数类型%28(如果有%29)到其类类型的隐式转换。注意,非显式用户定义的转换函数还指定隐式转换。
隐式声明和用户定义的非显式复制构造函数和移动构造器正在转换构造函数。
例
二次
struct A
{
A() { } // converting constructor (since C++11)
A(int) { } // converting constructor
A(int, int) { } // converting constructor (since C++11)
};
struct B
{
explicit B() { }
explicit B(int) { }
explicit B(int, int) { }
};
int main()
{
A a1 = 1; // OK: copy-initialization selects A::A(int)
A a2(2 // OK: direct-initialization selects A::A(int)
A a3{4, 5}; // OK: direct-list-initialization selects A::A(int, int)
A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int)
A a5 = (A)1; // OK: explicit cast performs static_cast, direct-initialization
// B b1 = 1; // error: copy-initialization does not consider B::B(int)
B b2(2 // OK: direct-initialization selects B::B(int)
B b3{4, 5}; // OK: direct-list-initialization selects B::B(int, int)
// B b4 = {4, 5}; // error: copy-list-initialization selected an explicit constructor
// B::B(int, int)
B b5 = (B)1; // OK: explicit cast performs static_cast, direct-initialization
B b6; // OK, default-initialization
B b7{}; // OK, direct-list-initialization
// B b8 = {}; // error: copy-list-initialization selected an explicit constructor
// B::B()
}
二次
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。