繁体   English   中英

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

[英]Why const char* implicitly converted to bool rather than 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;
}

output:

mystruct Bool 1
  1. 为什么const char*隐式转换为bool而不是std::string ,尽管构造函数需要explicit类型?
  2. 隐式转换优先级如何应用在这里?

因为从const char*bool的隐式转换被限定为标准转换,而const char*std::string是用户定义的转换。 前者排名较高,在 重载决议中胜出。

标准转换序列始终优于用户定义的转换序列或省略号转换序列。

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

直接初始化比复制初始化更宽松:复制初始化只考虑非显式构造函数和非显式用户定义转换函数,而直接初始化考虑所有构造函数和所有用户定义转换函数。

关于explicit说明符

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

“为什么const char*隐式转换为bool而不是std::string ,尽管构造函数需要explicit类型?”:

  • 标准转换优先于用户定义的转换。

char const*是一个指向常量字符的指针,并且指针可以隐式转换为bool :如果它是nullptr ,则将其转换为false ,否则转换为true

  • 您曾经在检查指针是否为NULL的情况下看到这种有效的转换,所以如果它不是nulptr我们安全地取消引用它,否则它具有nullptr值因此取消引用它是不正确的:

     int* ptr = nullptr; if(ptr) // false because ptr has nullptr or NULL or 0 or 0x000000 address value std::cout << ptr << '\t' << *ptr << '\n'; // not executed ptr = new int(10); // valid and non-nullptr if(ptr) // non-nullptr so condition succeeds std::cout << ptr << '\t' << *ptr << '\n'; // 0FED155 10 delete ptr; // free memory
  • explicit构造函数意味着它只能被显式调用,唯一的方法是通过直接初始化,就像你的情况一样:

     mystruct obj(c); // direct initialization mystruct obj = c; // copy-initialization. Error: constructor myStruct(bool) is `explicit`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM