2011-06-29 63 views
0
#include <iostream> 
int test(const double *t1,const double **t2) 
{ 
    return 0; 
} 
int main(int argc, char*argv[]) 
{ 
    double *t1 = new double; 
    const double ** t2 = new double *; 
    test(t1, t2); 
} 

的錯誤是:爲什麼下面的C++代碼不能編譯?

cannot convert double ** to const double ** 

它編譯如果我刪除了2 occurence的const雖然..

+1

什麼是錯誤? –

+2

@Diff。他清楚地說明了錯誤是什麼 - 除非他編輯了它,並且沒有被編輯。 – Puppy

+0

可能的重複[爲什麼以下給我一個轉換錯誤從雙***到const雙***](http://stackoverflow.com/questions/1404738/why-does-the-following-give-me -a-conversion-error-from-double-to-const-double) – Suma

回答

3

讓它

const double ** t2 = new const double *;

+0

@ Diff.Thinkr,不是'new const double *;'和'new double *;'是一樣的嗎?爲什麼'new'需要知道它是否是'const',因爲它只是從堆中分配空間? – Learning

+0

這可能會回答你的疑問... http://stackoverflow.com/questions/1927477/can-a-heap-allocated-object-be-const-in-c –

+0

這給了一個更好的解釋http:// stackoverflow。 com/questions/1370042/why-is-const-correct-specific-to-c/1370121#1370121 –

2

的問題是,由德 - 以某種方式引用,你可以用雙指針違反const的正確性。

+0

那是什麼'某種方式'? – Learning

+0

@學習:我記不起來了。 – Puppy

+0

http://stackoverflow.com/questions/1404738/why-does-the-following-give-me-a-conversion-error-from-double-to-const-double/1404795#1404795 –

0

至少應該編譯現在

int main(int argc, char*argv[]) 
{ 
    double *t1 = new double; 
    const double ** t2 = new const double *; 
    test(t1, t2); 
} 
0

這種轉換是不允許的,因爲如果轉換將是可能的,你可以修改const對象的方式如下:

#include <stdio.h> 

const double A0 = 0; 
const double A1 = 1; 
const double* A[2] = { &A0, &A1 }; 
double * B[2]; 

int main() 
{ 
    double** b = B; 
    const double ** a = b; // illegal 
    //const double ** a = (const double **)b; // you can simulate it would be legal 

    a[0] = A[0]; 
    b[0][0] = 2; // modified A0 

    printf("%f",A[0][0]); 
} 

對於一個模擬的結果,檢查code at IdeOne.com - 你將得到SIGSEGV(const對象被放置在只讀內存中,並且你試圖修改它)。使用不同的平臺時,對象可能會被靜默地修改。