从双/ INT /字符串自动转换在C ++ bool的 [英] Automatic conversion from double/int/string to bool in C++
问题描述
我是谁一直努力学习一点C ++就在旁边对我的知识扩展的Java程序员。这里是一个小code段,我的认为的作品由于隐式转换,但我想知道哪些规范的一部分它是指什么是其他规则,我必须知道,当涉及到隐式转换。是否有一个文件/链接/站点那里它规定了隐式转换规则?
I'm a Java programmer who has been trying to learn a bit of C++ on the side to expand on my knowledge. Here is a small code snippet which I think works due to implicit conversion but I'd like to know which part of the specification does it refer to and what are the other rules which I must be aware of when it comes to implicit conversion. Is there a document/link/site out there which lays down the implicit conversion rules?
#include <vector>
#include <iostream>
#include <iterator>
int main(void) {
using namespace std;
vector<bool> a;
a.push_back("asdf");
a.push_back("");
a.push_back(12);
a.push_back(0.0);
copy(a.begin(), a.end(), ostream_iterator<bool>(cout, "\n"));
return 0;
}
/*
output:
1
1
1
0
*/
TIA,结果
佐助
TIA,
sasuke
推荐答案
指针和整数,并且也布尔值,是的整型的。前三个都是要么指针或整数,因为它们是所有非零,他们转换为布尔值真正
。类型的第四个值双击
转换成一个零积分值,因此假
。
Pointers and integers, and also booleans, are integral types. The first three are all either pointers or integers, and since they are all non-zero, they convert to the boolean value true
. The fourth value of type double
converts to a zero integral value and hence false
.
这不会再presentable作为积分值(如无穷大和NaN)双打的转换是不确定的。
Conversion of doubles that are not representable as integral values (like infinity and NaN) is undefined.
请参阅4.9的详细信息,并且还4.12布尔转换:
See 4.9 for details, and also 4.12 for "Boolean conversions":
算术,无范围枚举,指针,或指针到成员A型prvalue可以被转换成一个
bool类型的prvalue。零值,空指针值或空成员指针值转换为false;
任何其他值转换为真实的。
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.
您 0.0
是一个算术类型的零值。
Your 0.0
is an arithmetic type of zero value.
也许你可能不熟悉C字符串++:,
表示数组的char [1] {0}
,和这个阵列(一个元件)衰变到一个指针到它的第一个元素,这是必然的非空指针。同样,ASDF表示数组的char [5] {A,S,D,F,0}
,再此衰减到一个(非空)指针到它的第一个元素。字符的实际值是完全无关紧要的。
Perhaps you may not be familiar with string literals in C++: ""
denotes the array char[1] { 0 }
, and this array (of one element) decays to a pointer to its first element, which is necessarily a non-null pointer. Similarly, "asdf" denotes an array char[5] { 'a', 's', 'd', 'f', 0 }
, and again this decays to a (non-null) pointer to its first element. The actual value of the characters is entirely immaterial.
这篇关于从双/ INT /字符串自动转换在C ++ bool的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!