2010-10-21 111 views

回答

13

什麼都沒有。

A const限定符適用於立即在其左邊的任何東西。如果左邊沒有任何東西,那麼它適用於右邊的任何東西。

+2

但是有'const int的* A','INT * const的A'和'const int的* const的A'之間的差。 – Benoit 2010-10-21 06:54:38

+3

@Benoit:是的,有。 – 2010-10-21 06:55:06

+0

哦,非常感謝。 – Naruto 2010-10-21 06:58:06

6

在這種情況下,沒有任何區別。

當你有一個指針或引用,這一變化可能幾乎相同顯著雖然。鑑於這樣的:

T * a; 

const(或volatile)相對於星號的位置是顯著:

T const * a; 
T * const a; 

第一個說a是一個指向const T(即你不能修改a引用的T對象)。第二個說a是一個(非const)T的一個常量 - 即,你可以修改a,但你不能修改指針本身,所以你不能指向它在一個不同的對象。當然,你也可以做兩種:

T const * const a; 

這意味着你不能改變指針本身T對象時,它指的是。

2

如果您使用簡單類型(嵌入或自定義),那麼這是一個品味問題。

在使用指針的情況下有一個簡單的通用規則:如果const放在'*'之前,那麼指向的數據是常量,否則指針本身是常量,你不能改變它的值。

例如:

const int a=1; // 'a' value can't be changed 
const int* q; // the data that 'a' point to is constant 
int const* q; // the same 
int* const p=&a; // the pointer is constant: const is behind '*' 

所以

int b=2; 
p = &b; // error: trying to change constant pointer 
相關問題