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

标签 c++ implicit-conversion overload-resolution explicit constructor-overloading

#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中获胜。 .

    A standard conversion sequence is always better than a user-defined conversion sequence or an ellipsis conversion sequence.


    顺便说一句:mystruct obj(c);执行 direct initialization , explicit转换构造函数,包括 mystruct::mystruct(bool)也被考虑。结果,c转换为 bool然后传递给 mystruct::mystruct(bool)作为构造 obj 的参数.

    Direct-initialization is more permissive than copy-initialization: copy-initialization only considers non-explicit constructors and non-explicit user-defined conversion functions, while direct-initialization considers all constructors and all user-defined conversion functions.


    关于 explicit specifier ,
    1. Specifies that a constructor or conversion function (since C++11) or deduction guide (since C++17) is explicit, that is, it cannot be used for implicit conversions and copy-initialization.

    关于c++ - 为什么 const char* 隐式转换为 bool 而不是 std::string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66452781/

    相关文章:

    c++ - <STL_hashtable> 中是否不需要构造函数参数

    c++ - 这有多线程安全?

    c++ - 不可行函数模板的类型推导

    c - 为什么未定义大小的数组只允许在 main() 中使用?

    c++ - 为什么这个 operator= 调用不明确?

    c++ - 当给定 const char * 作为模板化参数的类型时,为什么编译器选择 bool 而不是 string_view?

    c++ - 如何调用与成员函数同名的内联友元函数?

    c++ - 从段错误中恢复的最佳实践

    C++ 第一次编译

    c++ - 基于其他模板定义从模板类到原始类型的隐式转换