如下這段代碼,編譯報錯:
Error : initial value of reference to non-const must be an lvalue
#include <iostream> using namespace std; void test(float *&x){ *x = 1000; } int main(){ float nKByte = 100.0; test(&nKByte); cout << nKByte << " megabytes" << endl; }
原因為test函數的參數是個引用, 你有可能修改這個引用本身的值(不是引用指向的那個值),這是不允許的。
所以一個修復辦法為聲明引用為const,這樣你告訴編譯器你不會修改引用本身的值(當然你可以修改引用指向的那個值)
修改版1:
void test(float * const &x){ *x = 1000; }
另一個更簡單的修改辦法是直接傳遞指針,
修改版2:
void test(float * x){ *x = 1000; }
reference:
http://stackoverflow.com/questions/17771406/c-initial-value-of-reference-to-non-const-must-be-an-lvalue