2011-09-05 189 views
3

我無法解釋自己以下代碼:關於C++中const指針的問題?

double d = 100; 

    double const d1 = 30; 

    double* const p = &d; // Line 1 
    double* const p1 = &d1; // Line 2 

在上面的代碼,Line 1是好的,但Line 2產生錯誤:

"error C2440: 'initializing' : cannot convert from 'const double *__w64 ' to 'double *const '" 

誰能詳細說說嗎?我正在使用VS C++ 2005,在Win XP SP3上運行)

+3

請閱讀:http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.5 –

回答

10

double* const類型是一個指向非const double的const指針。如果你想要一個指向const double的指針,你必須使用double const*(或者如果你想要一個const指針指向一個const double,則使用double const* const)。

在C++中,通過一個簡單的指針指向一個double,你指針本身(即,你能指向另一個位置)的常量和值的常量(你可以改變通過指針的值)可以獨立配置。這給你四個非常相似,但不相容類型:

double const* const p1; // Const pointer to const double 
         // . you can't have the pointer point to another address 
         // . you can't mutate the value through the pointer 

double const* p2;  // Non-const pointer to const double 
         // . you can have the pointer point to another address 
         // . you can't mutate the value through the pointer 

double* const p3;  // Const pointer to double 
         // . you can't have the pointer point to another address 
         // . you can mutate the value through the pointer 

double* p4;    // Non-const pointer to non-const double 
         // . you can have the pointer point to another address 
         // . you can mutate the value through the pointer 
+1

這意味着他需要使用'double const * const',對吧? – wormsparty

+0

@wormsparty:他不需要,不。 'double const * p2 = &d1;'很好。 'p'和'p1'的定義中的'const'防止它們在後來被更改爲包含不同的地址,所以如果他需要的話,除了需要能夠指向'const double',例如'd1',那麼他需要'double const * const'。 –

+0

因爲d1是一個const int,所以它會這樣做:const double * p1 = &d1; – Gob00st

4

double * const p1的聲明const指針非constdouble,即指針可以改變(即它可以重新尖),但沒有的事它指向的是。但是d1const

你的意思是:

const double* p = &d; // Line 1 
const double* p1 = &d1; // Line 2 

[見從C++ FAQ this question]

+0

我建議編寫'double const *'。它等同於'const double *',但是你可以用簡單的規則「const應用於它前面的所有內容」而不需要額外的規則。「const在開頭適用於最內層的類型」。 –

+0

@Jan:我看到你的邏輯,但最終它是個人偏好。我讀了上面的定義,「p是一個指向const double的指針」;對我而言,這並不令人困惑。 –

+1

@Jan:就我個人而言,我認爲以您的方式教授它的一個主要好處是編寫'const'首先誘使人們認爲'typedef char * cptr; typedef const cptr ccptr;'與'typedef const char * ccptr;'相同。他們不太可能認爲,如果他們一直寫'typedef char const * ccptr;'。即便如此,我還是傾向於寫出奧利賦予自由的方式,並且在相關新聞中,也寫'const int i = 0;'而不是'int const i = 0;'。 –

2

如果你讀聲明從右到左這是比較容易:

double const *  p; // pointer to const double 
const double *  p; // pointer to const double 
double  * const p; // const pointer to double 
double const * const p; // const pointer to const double 
0

你可以很容易理解的代碼以下列方式。

double const d1 = 30; 
double* const p1 = &d1; 

這裏在第2行,問題是我們正在給常量值賦予一個常量值d1,這個常量值可以在將來改變。

如果我們瞭解左側值的右側數據類型,會更容易。

在我們的例子中,右側的數據類型可以被當作是指向const double的指針,其中左側是一個指向double的指針,這個指針相反並且引發了一個compilor錯誤。