2016-09-06 53 views
3

我不明白,常量T * &是指針爲const類型T的引用指針低級別的常量,這樣它不會改變的價值指向至。但是,下面的代碼失敗在編譯時並給出了以下消息:不能從int *轉換參數const int的*

error C2664: 'void pointer_swap(const int *&,const int *&)': cannot convert argument 1 from 'int *' to 'const int *&'. 

有什麼辦法來修改指針,但防止它指向的指針從函數變化?

void pointer_swap(const int *&pi, const int *&pj) 
{ 
    const int *ptemp = pi; 
    pi = pj; 
    pj = ptemp; 
} 

int main()                 
{          
    int i = 1, j = 2;     
    int *pi = &i, *pj = &j;   
    pointer_swap(pi, pj); 
    return 0; 
} 
+1

你有一個'INT *'而且需要'const int的*'作爲輸入。所以把pi和pj改爲'const int *'可以修復錯誤。我不知道爲什麼沒有從非const到const的隱式轉換。 – Hayt

+1

@Hayt - 由於參考。這將允許函數來執行類似'PI = something_that_really_is_const;',那麼這將允許呼叫者修改'something_that_really_is_const'。 –

+0

啊有道理。謝謝:) – Hayt

回答

0

使pi和pj在主函數中const。

#include <iostream> 
using namespace std; 

void pointer_swap(const int *&pi, const int *&pj) 
{ 
    const int *ptemp = pi; 
    pi = pj; 
    pj = ptemp; 
} 

int main()                 
{          
    int i = 1, j = 2;     
    const int *pi = &i, *pj = &j;   
    pointer_swap(pi, pj); 
    return 0; 
} 
+1

你還可以解釋爲什麼這是這種情況,爲了一個完整的答案? – Hayt

+0

@Hayt現在我看到你在評論中也提出了同樣的解決方案。我的壞> :( –

+0

我只是沒有把它作爲一個答案,因爲我不能拿出一個爲什麼在這一點上,如果你這一點。 – Hayt

3

你不能這樣做,因爲你不能綁定參考-TO-const的引用給非const*

你可以推出自己的,但它更有意義只使用std::swap,這是明確的爲此而設計的,並完全通用:

#include <algorithm> 

std::swap(pi, pj); 

[Live example]


*因爲這樣會允許這樣的事情:

int  *p = something_non_const(); 
const int *q = something_really_const(); 
const int *&r = p; 
r = q;  // Makes p == q 
*p = ...; // Uh-oh 

0

這是我的想法。希望能幫助你。

void fun1(const int * p) 
{ 
} 

int * pa = 0; 
fun1(pa); //there is implicit conversion from int * to const int * 

void fun2(const int & p) 
{ 

} 
int a = 0; 
fun2(a); //there is implicit conversion from int & to const int &. 

兩個例子表明,編譯器會幫助我們,使從電流型轉換爲const電流型。因爲我們告訴編譯器參數是const。

現在

,看看這個:

void fun3(const int * &p) 
{ 
//this declaration only states that i want non-const &, it's type is const int * . 
} 

int *pi = 0; 
fun3(pi); // error C2664 

從非const到你希望沒有發生,因爲該函數的聲明只是說我想非const &常量的隱式轉換,它的類型是const int *。

相關問題