繁体   English   中英

C ++中的指针和const

[英]Pointers and const in C++

处理指针和const时,我看到有三种声明它们的方法:

1)

int nValue = 5;
int *const pnPtr = &nValue;

2)

int nValue = 5;
const int *pnPtr = &nValue;

3)

const int 5;
const int *const pnPtr = &nValue;

示例1被称为“指向非常量的常量指针”。 地址不能更改,但值可以更改。 因此,我们可以执行以下操作,因为示例1中的nValue是非常量int:

int nValue = 5;
int const *pnPtr = &nValue;

*pnPtr = 6; 

但是我们无法在示例1中执行以下操作:

int nValue = 5;
int nValue2 = 6;
int const *pnPtr = &nValue;
pnPtr = &nValue2; 

示例2被称为“指向const的指针”。 这意味着地址可以更改,但值不能更改。 我们可以执行以下操作:

int nValue = 5;
int nValue2 = 6;

const int *pnPtr = &nValue;
pnPtr = &nValue2;

但是我们无法在示例2中执行以下操作:

int nValue = 5;
int nValue2 = 6;

const int *pnPtr = &nValue;
*pnPtr = nValue2;

示例3是“指向const的const指针”。 这意味着地址或值都不能更改:

const int nValue;
const int *const pnPtr = &nValue;  

我的问题与第二个示例有关。 当nValue不是const时,为什么第二个示例称为“指向const的指针”。 这是一个常规的int声明。 另外,在第二个示例中,如果当我们给它分配另一个地址时,该另一个地址具有不同的值,我们不能仅仅遵从该地址并返回不同的值怎么办? 那不会破坏整个目标吗?

第二个示例中的const适用于int ,即您具有指向const int的非const指针。 由于C和C ++中的类型是从右到左读取的,因此实际上最容易将const始终放在右边。 它也是唯一可以一致放置的地方:

int i(0);
int      *       p0(&i); // non-const pointer to non-const int
int const*       p1(&i); // non-const pointer to const int
int      * const p2(&i); // const pointer to non-const int
int const* const p3(&i); // const pointer to const int

也就是说,您可以将const应用于指针(可以更改p0p1但不能更改p2p3 ),也可以将const应用于指针所指向的实体(可以更改*p0*p2但不能更改*p1*p3改变)。 对于第二行和第四行,您可以交换intconst但我建议不要这样做。

在C语言中,即使整数也不是常量,但是在处理常量整数时我们声明了指针。 在这种情况下,C在将整数分配给指针的引用时会将其隐式转换为常数。

通常,我们在将一些值传递给函数时会执行此操作,这样可以避免某些意外更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM