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说明符,