且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对非常量的引用的初始值必须是左值

更新时间:2023-11-11 23:01:22

当您通过非const 引用传递指针时,您是在告诉编译器您将要修改该指针的值.您的代码不会这样做,但编译器认为会这样做,或者计划在将来这样做.

要修复此错误,请声明 x 常量

//这告诉编译器你不打算修改指针//通过引用传递无效测试(浮动*常量&x){* x = 1000;}

或者创建一个变量,在调用test之前将指针分配给nKByte:

float nKBy​​te = 100.0;//如果test()"决定修改`x`,则修改会反映在nKBytePtr中float *nKBytePtr = &nKByte;测试(nKBytePtr);

I'm trying to send value into function using reference pointer but it gave me a completely non-obvious error

#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

I have no idea what I must do to repair above code, can someone give me some ideas on how to fix that code?

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

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

or make a variable to which you assign a pointer to nKByte before calling test:

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