我的问题是,根据我的示例,我已经能够通过指针指向一个非常量变量,该指针指向一个常量变量。我的样本是这样的: -
int tobepointed = 10;
int tobepointed1 = 11;
int const *ptr = &tobepointed;
cout << "\nPointer points to the memory address: " << ptr;
cout << "\nPointer points to the value: " << *ptr;
tobepointed = 20;
cout << "\nPointer points to the memory address: " << ptr;
cout << "\nPointer points to the value: " << *ptr;
ptr = &tobepointed1;
cout << "\nPointer points to the memory address: " << ptr;
cout << "\nPointer points to the value: " << *ptr;
现在这段代码正常运行,没有任何编译或运行时错误。
还要考虑指针* ptr。如果我像任何普通指针一样声明ptr: -
int *ptr;
那么输出也是一样的,为什么我们需要'指向常数'的概念?
是的我同意'常量指针'的概念,但“概念指针”似乎毫无用处。
答案 0 :(得分:3)
指向常量的指针应指向...常量int。您的程序会编译,因为您指的是tobepointed
int
。
如果你声明它const int
,那么指向它(没有强制转换)的唯一方法就是使用const int*
:
const int tobepointed = 10;
const int* ptr = &tobepointed;
如果你试图创建非常量指针:
const int tobepointed = 10;
int* ptr = &tobepointed;
编译器would complain:
错误:来自&#39; const int *&#39;的无效转换到&#39; int *&#39;