我目前正在尝试学习一些C++,并遇到以下不直观的行为。由于t
是指向const int
的指针,我希望*t
保持不变,只要我们不改变t
即可。为什么常量整数指针指向一个非常量整数?
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int a = 3;
const int* t = &a; //Why is this allowed? a is NOT const int
a = 4;
cout << *t << endl; //This does then print 4
//*t = 4; //Throws error.
return 0;
}
任何人都可以解释为什么这是编译?
为了澄清我会建议没有指针的混乱。 'int a = 1; const int b = a;'就好了,现在'b'是const,而'a'不是,即使保持相同的值 – user463035818
@ tobi303是的,但是在你的例子中'b'接收* copy * of 'a'的值。 – flawr
那么,那么'int a = 1; const int&b = a;'now'b'是'b'的一个引用,但是即使'a'不是const也不能通过'b'改变这个值 – user463035818