为什么没有输出101
当我分配了之前的x
到新的x
?
int x = 101;
{
int x = x;
std::cout << x << std::endl;
}
输出(垃圾):
422634
我以为是第二个x
将被初始化为101
但它没有初始化。
注:本例的解决方案是int x = ::x
但问题是why它发生了。
申报点
名称的声明点是在其完成之后立即
声明符及其初始化程序之前... [C++ 标准 § 3.3.2/1]
当编译器足够了解声明符时,它就会完成声明。
上面的代码等同于下面的代码:
int x = 101;
{
int x;
x = x; <------------------// Self assignment, assigns an indeterminate value.
std::cout << x << std::endl;
}
因为,内心的宣言x
之前完成=
(任务)
int x = x; <--// Now, we have the new `x` which hides the older one,
^ // so it assigns itself to itself
|
+---// Point of declaration,
// here compiler knows everything to declare `x`.
// then declares it.
另一方面,当我们声明复杂对象时,声明的点就更远了。所以,行为是不同的。
例如下面的代码就OK
const int i = 2;
{
int i[i];
^
|
+----// Point of declaration
// compiler has to reach to "]"
// therefore before declaring `i` as an array
// there is just one `i`, the `i` of `const int i=2`
}
在上面的代码中,编译器必须知道数组的实际大小才能完成声明,因此声明的重点是]
。因此i
within [i]
是外层i
因为声明i
of int i[...
尚未完成。因此,它声明了一个数组2
元素(int i[2];
).
此外,此示例还显示了枚举数的声明点
const int x = 12;
{
enum { x = x };
^
|
+---// Point of declaration
// compiler has to reach to "}" then
// there is just one `x`, the `x` of `const int x=12`
}
枚举器x
用常量的值初始化x
,即12
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)