为什么 const char* 隐式转换为 bool 而不是 std::string?

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)
  1. 为什么const char*隐式转换为bool而不是std::string,虽然构造函数需要explicit类型?
  2. 隐式转换优先级在这里如何应用?

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

  1. 指定构造函数or conversion function (since C++11) or deduction guide (since C++17)是显式的,也就是说,它不能用于隐式转换复制初始化

  • 它会阻止意外转换,例如:https://godbolt.org/z/heErYe 或 https://godbolt.org/z/7hWdon,如果您无法按照您编写的方式调用显式构造函数d 根本无法调用该构造函数 (4认同)