2013-10-06 43 views
1

考慮下面的代碼:C++不能從 '詮釋**' 轉換爲 'const int的**'

int** a; 
const int** b; 
b = a; 

該代碼給出了一個錯誤:

error C2440: '=' : cannot convert from 'int **' to 'const int **' 
Conversion loses qualifiers 

爲什麼我不能演員演員?

當操作簡單的指針時,它工作正常。

int* a; 
const int* b; 
b = a; 
+1

我認爲這兩個都不應該是可能的。 – JSQuareD

+0

在你的第一種情況下'const'是什麼內在的'int',這個const不能在賦值中被丟棄。 –

+0

http://c-faq.com/ansi/constmismatch.html – P0W

回答

3

假設您能夠執行此演員表。試想一下:

const int n = 42; 
const int* cp = &n; 

int* p; 
int** a = &p; 

const int** b; 
b = a; // hypothetical, doesn't compile 
*b = cp; // equivalent to p = cp; 
*p = 84; // equivalent to n = 84: oops 

因此,允許從int**const int**隱式轉換將允許程序違反const正確性。