这段代码:
int scores[] {1,2,3,4};
int *score_ptr {scores};
//let's say that initial value of score_ptr is 1000
std::cout<<*score_ptr++;
产生输出:
1
由于*
与++
具有相同的优先级,然后关联是从右到左难道我们不应该适用++
第一家运营商也就是先增加指针*
(间接引用)吗?
因此,score_ptr
将相应地增加到1004
,然后对其取消引用将给出分数的第二个元素,即2
。
为什么以及为什么这会给我输出1
而不是2
?
由于
*
与++
具有相同的优先级
不,后缀operator++
具有更高的优先级比operator*
; 然后*score_ptr++
等于*(score_ptr++)
。请注意,后缀operator++
将增加操作数并返回原始值,然后*(score_ptr++)
给出值1
。
结果是操作数原始值的prvalue复制。
另一方面,前缀operator++
返回递增的值。如果将代码更改为*++score_ptr
(等于*(++score_ptr)
),则结果将是2
(可能是您期望的结果)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句