引用非const的C ++初始值必须为左值 [英] C++ initial value of reference to non-const must be an lvalue
问题描述
我正在尝试使用引用指针将值发送到函数中,但这给了我一个完全非显而易见的错误
I'm trying to send value into function using reference pointer but it gave me a completely non-obvious error to me
#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();
}
错误:对非const的引用的初始值必须为左值
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? thanks :)
推荐答案
当您通过非const
引用传递指针时,您将告诉编译器您将要修改该指针的值.您的代码没有做到这一点,但是编译器认为它已经做到了,或者计划在将来做到这一点.
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.
要解决此错误,请声明x
常量
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;
}
或创建一个变量,在调用test
之前将其分配给nKByte
指针:
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);
这篇关于引用非const的C ++初始值必须为左值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!