我很惊讶c++允许对常量数据的解引用指针进行递增操作,而对const数据的指针则不允许。考虑以下代码:
#include<iostream>
#include<climits>
using namespace std;
int main(){
int x = 2;
const int *xPtr2 = &x;
*xPtr2++;
cout << x << endl;
}
但是x的值仍然是2。这意味着*xPtr2实际上并没有增加。我还尝试了*xPtr2 = 3,但这次显示了编译错误。为什么会这样呢?
此处++的优先级高于*。因此
*xPtr2++
等价于
*(xPtr2++)
由于xPtr2不是常量指针,而是指向常量数据的指针,因此在这种情况下(但在其他情况下)对xPtr2进行递增和解引用是可以的,因此不会导致编译错误。
++
操作符优先于解引用。基本上,你是在对已加的指针解引用。
对于你想要完成的行为,你应该把指针包装在parent中。
(*xPtr2)++;
同样适用于分配-您试图将int
分配给int *
。这对父母来说是有效的。
(*xPtr2) = 3;
您提到过
指向常量数据的解引用指针那么,让我们考虑下面的代码
#include <stdio.h>
int main() {
const int foo = 0xdead;
int* bar = (int*) &foo;
*bar = 0xcafe;
printf("const int foo = %#x", foo);
return 0;
}
输出:const int foo = 0xcafe
在C语言中,c++ const
只是变量的编译时修饰符。这意味着编译器不希望在编译时修改const
。在运行时没有const
=>的概念,所有的局部变量都存储在堆栈中,所有的static
和全局变量都存储在.data
section中。因此,只能在运行时