如何解决为什么 const char* 隐式转换为 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*
到 bool
的隐式转换被限定为标准转换,而 const char*
到 std::string
是用户定义的转换。前者排名更高,在overload resolution中获胜。
标准转换序列总是优于用户定义的转换序列或省略号转换序列。
顺便说一句:mystruct obj(c);
执行 direct initialization,也考虑了 explicit
转换构造函数,包括 mystruct::mystruct(bool)
。结果,c
被转换为 bool
,然后传递给 mystruct::mystruct(bool)
作为构造 obj
的参数。
直接初始化比复制初始化更宽容:复制初始化只考虑非显式构造函数和非显式用户定义的转换函数,而直接初始化考虑所有构造函数和所有用户定义的转换函数。>
- 指定构造函数
or conversion function (since C++11)
or deduction guide (since C++17)
是显式的,即不能用于 implicit conversions 和 copy-initialization。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。