为什么constchar*隐式转换为bool而不是std::string?
#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;
}
输出:
mystruct Bool 1
- 为什么
const char*隐式转换为bool而不是std::string,虽然构造函数需要explicit类型? - 隐式转换优先级在这里如何应用?
回答
因为从const char*to的隐式转换bool被限定为标准转换,而const char*tostd::string是用户定义的转换。前者具有更高的排名,并且在超载决议中获胜。
标准转换序列总是优于用户定义的转换序列或省略号转换序列。
顺便说一句:mystruct obj(c);执行直接初始化,也考虑explicit转换构造函数mystruct::mystruct(bool)。结果,c被转换为bool然后mystruct::mystruct(bool)作为参数传递给construct obj。
直接初始化比复制初始化更宽容:复制初始化只考虑非显式构造函数和非显式用户定义转换函数,而直接初始化考虑所有构造函数和所有用户定义转换函数。
关于explicit说明符,
- 指定构造函数
or conversion function (since C++11)or deduction guide (since C++17)是显式的,也就是说,它不能用于隐式转换和复制初始化。
- It stops accidental conversions, e.g: https://godbolt.org/z/heErYe or https://godbolt.org/z/7hWdon, if you couldn't call an explicit constructor in the way you've written it you'd never be able to call that constructor at all
THE END
二维码