我有些不明白。在下面的代码中我定义了一个整数和一个常量整数。
我可以让一个常量指针(int* const)指向一个整数。参见第四行代码。
同一个常量指针(int* const)不能指向常量整数。见第五行。
指向 const 的常量指针(const int* const)可以指向常量整数。这就是我所期望的。
但是,相同的 (const int* const) 指针允许指向非常量整数。请参阅最后一行。为什么或如何可能?
int const constVar = 42;
int variable = 11;
int* const constPointer1 = &variable;
int* const constPointer2 = &constVar; // not allowed
const int* const constPointer3 = &constVar; // perfectly ok
const int* const constPointer4 = &variable; // also ok, but why?
int const constVar = 42; // this defines a top-level constant
int variable = 11;
int *const constPointer1 = &variable;
int *const constPointer2 = &constVar; // not allowed because you can change constant using it
const int *const constPointer3 = &constVar; // perfectly ok. here you can't change constVar by any mean. it is a low level constant.
const int *const constPointer4 = &variable; // also ok, because it says you can't change the value using this pointer . but you can change value like variable=15 .
*constPointer4=5; //you get error assignment of readonly location.because that pointer is constant and pointing to read only memory location.
您始终可以决定不修改非常量变量。
const int* const constPointer4 = &variable;
只需解析定义:
constPointer4
是一个const(即你不能再更改它指向的内容)指向const int(即variable
)的指针。这意味着您无法通过variable
修改 constPointer4
,即使您可以通过其他方式修改
variable
。
另一种方式(通过非常量指针访问 const 变量),您将需要一个
const_cast
。
为什么指向 const 的指针有用?它允许您在类中拥有
const
成员函数,您可以向用户保证该成员函数不会修改对象。
const 的访问权限比非 const 少,这就是允许它的原因。您将无法通过指针更改“变量”,但这并不违反任何规则。
variable = 4; //ok
*constPointer4 = 4; //not ok because its const
在调用函数时,您经常使用这种“指向非 const 变量的 const 指针”的情况。
void f(const int * const i)
{
i=4; //not ok
}
f(&variable);
指向 const 对象的指针不能用于修改该对象。别人能否修改并不重要;它只是无法通过该指针完成。
int i; // modifiable
const int *cip = &i; // promises not to modify i
int *ip = &i; // can be used to modify i
*cip = 3; // Error
*ip = 3; // OK
第 4 行:
int* const constPointer2 = &constVar;
这里不应该允许,因为
int* const
的int* const constPointer2
部分意味着指针是常量,然后你继续将它赋值给&constVar
。