我正在尝试使用引用指针将值发送到函数中,但它给了我一个完全不明显的错误
#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();
}
Error : initial value of reference to non-const must be an lvalue
我不知道我必须做什么来修复上述代码,有人能给我一些关于如何修复该代码的想法吗?
最佳答案
当您通过非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;
}
或在调用 test
之前创建一个变量,为该变量分配一个指向 nKByte
的指针:
float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);
关于c++ - 非常量引用的初始值必须是左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17771406/