"指针到常量"有什么用?

What is the use of 'pointer to constant'?

本文关键字:什么 常量 指针      更新时间:2023-10-16

我的问题是,根据我的样本,我已经能够通过指向常量变量的指针指向非常量变量。我的示例是这样的:-

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指针。如果我像任何普通指针一样声明ptrint *ptr;

然后输出也是相同的,所以为什么我们需要"指针指向常量"的概念?

是的,我同意"常量指针"的概念,但是"概念指针"看起来没有用处。

指向常量的指针应该指向…一个常量int。你的程序编译了,因为你指向的是tobepointed,而不是int

如果您声明它为const int,那么指向它(不强制转换)的唯一方法是使用const int*:

const int tobepointed = 10;
const int* ptr = &tobepointed;

如果你试图创建非const指针:

const int tobepointed = 10;
int* ptr = &tobepointed;

编译器会报错:

错误:从'const int*'到'int*'的转换无效