C++对非const的引用初始值必须是左值

Moh*_*ril 33 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();
}
Run Code Online (Sandbox Code Playgroud)

错误:对非const的引用的初始值必须是左值

我不知道我必须做些什么来修复上面的代码,有人能给我一些关于如何修复代码的想法吗?谢谢 :)

das*_*ght 43

当您通过非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;
}
Run Code Online (Sandbox Code Playgroud)

或者nKByte在调用之前创建一个指定指针的变量test:

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


wil*_*ilx 9

&nKByte创建一个临时值,它可以不被绑定到给非const的参考.

您可以更改void test(float *&x)void test(float * const &x)或者您可以完全放下指针并使用void test(float &x); /*...*/ test(nKByte);.


Som*_*ude 5

当您调用testwith 时&nKByte,address-of 运算符会创建一个临时值,您通常不能引用临时值,因为它们是临时的。

要么不要对参数使用引用,要么最好不要使用指针。