簡體   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