举个例子:
int main()
{
const char* what = "Is This";
what = "Interesting";
cout << *what;
what[3] = 'a'; // Sytax Error: expression must be a modifiable lvalue
cout << *what;
return 0;
}
因此我将what
声明为const char*
,并且我能够将其重新分配给另一个值(内存中的实际数据 - 而不是内存地址本身)。
但是,它告诉我,我无法改变第4位的角色!
这是为什么?
在这段代码中,what
是一个指向const char的非const指针。
你可以改变what
,但你不能改变*what
。
如果要声明const char的const指针,则需要编写两次const
:
const char *const what = "Is This";
// what is const
what = "Interesting"; // Error
// *what is also const
what[4] = 'x'; // Error
如果你想要一个指向非const char的const指针,请将它写在不同的地方:
char isthis[] = "Is This";
char interesting[] = "Interesting";
char *const what = isthis;
// what is const
what = interesting; // Error
// *what is not const
what[4] = 'x'; // Ok
const
适用于指向不是指针本身的字符!因此,您可以指向所需的任何C字符串,但不能更改这些字符串的字符。
为了简化示例,我将使用另一种类型来说明这一点(不能修改C字符串文字):
你实际上有这样的东西
const int i = 666;
const int j = 999;
const int *pi = &i;
pi = &j;
// *pi=444; is invalid, can't change the int pointed by pi
您可以构建一个无法更改但指向int的指针:
int i = 666;
int j = 999;
int *const pi = &i;
*pi = 999;
// pi = &j; is invalid, pi will always point to i
然后你可以将两者混合,永远不要改变指针,也不要改为指向int:
const int i = 666;
const int j = 999;
const int *const pi = &i;
// pi = &j; is invalid
// *pi = 444; is invalid