[英]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
const char*
隐式转换为bool
而不是std::string
,尽管构造函数需要explicit
类型? 因为从const char*
到bool
的隐式转换被限定为标准转换,而const char*
到std::string
是用户定义的转换。 前者排名较高,在 重载决议中胜出。
标准转换序列始终优于用户定义的转换序列或省略号转换序列。
顺便说一句: mystruct obj(c);
执行直接初始化,包括mystruct::mystruct(bool)
在内的explicit
转换构造函数也被考虑在内。 结果, c
被转换为bool
然后传递给mystruct::mystruct(bool)
作为构造obj
的参数。
直接初始化比复制初始化更宽松:复制初始化只考虑非显式构造函数和非显式用户定义转换函数,而直接初始化考虑所有构造函数和所有用户定义转换函数。
关于explicit
说明符,
“为什么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.