c++ - 非常量引用的初始值必须是左值

标签 c++ pointers reference

我正在尝试使用引用指针将值发送到函数中,但它给了我一个完全不明显的错误

#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/

相关文章:

c# - 旧的注释代码和代码中的大量空格会降低性能吗?

c - 使用另一个指针变量 char *c 操作和访问 char *s 指针变量(字符串) - C

java - 为什么当 grails 项目作为 grails-app 运行时,我的 java 项目中的包无法编译,java 项目引用了 grails 项目

java - 了解 Java 在用作方法参数时如何处理对象

c++ - 重置引用时为什么没有出现错误?

c++ - 循环失败

c++ - 带有 OO 的模板导致 Unresolved external symbol 问题

c++ - 如何判断您是否在 Windows 上编译?

C++ 通过引用传递对象?

c++ - char * (*arr)[2 ] 和 char **array[2] 有何不同?