pmp*_*pmp 8 c++ explicit constructor-overloading overload-resolution implicit-conversion
#include <iostream>
#include <string>
struct mystruct{
mystruct(std::string s){
std::cout<<__FUNCTION__ <<" String "<<s;
}
explicit mystruct(bool s) {
std::cout<<__FUNCTION__<<" Bool "<<s;
}
};
int main()
{
const char* c ="hello";
mystruct obj(c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
mystruct Bool 1
Run Code Online (Sandbox Code Playgroud)
const char*
隐式转换为bool
而不是std::string
,虽然构造函数需要explicit
类型?son*_*yao 11
因为从const char*
to的隐式转换bool
被限定为标准转换,而const char*
tostd::string
是用户定义的转换。前者具有更高的排名,并且在超载决议中获胜。
标准转换序列总是优于用户定义的转换序列或省略号转换序列。
顺便说一句:mystruct obj(c);
执行直接初始化,也考虑explicit
转换构造函数mystruct::mystruct(bool)
。结果,c
被转换为bool
然后mystruct::mystruct(bool)
作为参数传递给construct obj
。
直接初始化比复制初始化更宽容:复制初始化只考虑非显式构造函数和非显式用户定义转换函数,而直接初始化考虑所有构造函数和所有用户定义转换函数。
关于explicit
说明符,