尽管可能在某个地方回答了这个问题,但我找不到它。
下面写的第一条陈述起作用,而第二条没有?为什么?
int main() {
int x = 1, y = 2;
int *p = &++x; // First
std::cout << "*p = " << *p << std::endl;
// int *q = &x++; // Second
// std::cout << "*q = " << *p << std::endl;
}
尽管可能在某个地方回答了这个问题,但我找不到它。
下面写的第一条陈述起作用,而第二条没有?为什么?
int main() {
int x = 1, y = 2;
int *p = &++x; // First
std::cout << "*p = " << *p << std::endl;
// int *q = &x++; // Second
// std::cout << "*q = " << *p << std::endl;
}
在此声明中
there are used two unary operators: pre-increment ++ and taking of address. Unary operators are executed from right to left. So at first the variable
x
is incremented and its address is assigned to the pointer p,在此声明中
使用了postfix运算符post-increment ++和带地址的iunary运算符。后缀运算符相对于一元运算符具有优先级。因此,首先执行后增量。其结果是一个临时对象,该对象在递增之前具有变量x的值。然后执行地址获取操作符。
但是,您不能使用临时对象的地址。因此,对于此声明,编译器将发出错误。