2013-07-21 44 views
16

我想使用的參考指針發送值到的功能,但它給了我一個完全陌生的類型錯誤給我C++的參照非const初始值必須是一個左值

#include "stdafx.h" 
#include <iostream> 

using namespace std; 

void test(float *&x){ 

    *x = 1000; 
} 

int main(){ 
    float nKByte = 100.0; 
    test(&nKByte); 
    cout << nKByte << " megabytes" << endl; 
    cin.get(); 
} 

錯誤:初始非const的引用值必須是左值

我不知道我必須做些什麼來修復上面的代碼,有人可以給我一些關於如何修復該代碼的想法嗎?謝謝:)

+1

你能剛落指針,使用一個簡單的參考呢? –

+0

哈哈,現在因爲我在learncpp.com和該網站下面的教程教我如何在函數中使用引用指針,所以我也想試試它..:p btw謝謝@Micha Wiedenmann –

+0

只有當指針使用引用時你想修改函數外的指針。 –

回答

31

當您通過非const引用傳遞指針時,您告訴編譯器您將修改該指針的值。你的代碼沒有這樣做,但編譯器認爲它確實,或者計劃在將來做。

要修正這個錯誤,要麼宣佈x不斷

// This tells the compiler that you are not planning to modify the pointer 
// passed by reference 
void test(float * const &x){ 
    *x = 1000; 
} 

或使一個變量,你的指針分配給nKByte調用test前:

float nKByte = 100.0; 
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr 
float *nKBytePtr = &nKByte; 
test(nKBytePtr); 
+0

您的示例與解釋是真棒,所以我現在明白'臨時值',另外,你的解決方案'float * nKBy​​tePtr =&nKByte;'也與另一個答案不同,所以我有(必須!)選擇你的解答作爲答案。再次感謝: d –

3

當你調用test&nKByte,運營商地址的創建臨時值,你不能正常有臨時值的引用,因爲它們是,嗯,暫時的。

請不要使用參數作爲參數,或者更好的是不要使用指針。

+0

float nKBy​​te = 100.0; float * ptr =&nKByte;測試(PTR); – thomas

+0

@thomas是的,可以工作,但在這種情況下,不需要使用對指針的引用。 –

+0

感謝您的答案,我已經學習了新的東西,&nKByte創建一個臨時值,我不知道它,直到現在..再次感謝:) –

4

&nKByte創建一個臨時值,該值不能綁定到對非const的引用。

您可以將void test(float *&x)更改爲void test(float * const &x),或者您可以將指針完全放下並使用void test(float &x); /*...*/ test(nKByte);

+0

感謝您的快速答案,現在我明白了:) –

相關問題