Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 无法更改为无法写入的指针?_C++_C - Fatal编程技术网

C++ 无法更改为无法写入的指针?

C++ 无法更改为无法写入的指针?,c++,c,C++,C,如何声明这样的指针 我应该把这两个consts放在哪里 我假设C和C++中的情况是一样的。 < P> const int *const ptR /c>将工作。< /p> 最左边的const应用于int(指针对象),另一个const应用于其左边的,*,也称为指针 int main() { int i = 42; int b = 0; const int *const ptr = &i; ptr = &b; // doesn't compile *ptr =

如何声明这样的指针

我应该把这两个
const
s放在哪里


我假设C和C++中的情况是一样的。

< P> <代码> const int *const ptR /c>将工作。< /p> 最左边的
const
应用于int(指针对象),另一个
const
应用于其左边的,
*
,也称为指针

int main()
{
  int i = 42;
  int b = 0;
  const int *const ptr = &i;

  ptr = &b; // doesn't compile
  *ptr = 1; // dito
}

以下是
const
/non-
const
的四种变体,涉及指针及其指向的对象:

int i1 = 10;
const int i2 = 20;
int i3 = 30;
const int i4 = 40;

int* p1 = &i1;              // You can change p1 and *p1
*p1 = 25;                   // OK
p1 = &i3;                   // OK

const int* p2 = &i2;        // You can change p2 but not *p2
*p2 = 25;                   // Not OK
p2 = &i4;                   // OK

int* const p3 = &i1;        // You can not change p3 but you can change *p3
*p3 = 25;                   // OK
p3 = &i3;                   // Not OK

const int* const p4 = &i2;  // You can change neither p4 nor *p4
*p4 = 25;                   // Not OK
p4 = &i4;                   // Not OK

事实上,
p
的类型是
int-const**const

int-const**const
?(
const
指向
const
指针的指针)限定符始终应用于其剩余部分。除非它们在最左边。这个问题是关于指向指针的指针。这个问题是关于指向指针的指针。@ouah,我没有得到那种印象,但我可能弄错了。这个问题的标题是不能改成不能写入的指针?
typedef const int *pointer_that_cannot_be_written_through;
typedef pointer_that_cannot_be_written_through *const unwriteable_pointer;
int a;
pointer_that_cannot_be_written_through b = &a;
unwriteable_pointer p = &b, q = &b;
p = q;    // ERROR
*p = *q;  // FINE
**p = **q // ERROR