对非常量的引用的 C++ 初始值必须是左值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17771406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ initial value of reference to non-const must be an lvalue
提问by Mohd Shahril
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();
}
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 :)
我不知道我必须做什么来修复上面的代码,有人可以给我一些关于如何修复该代码的想法吗?谢谢 :)
回答by dasblinkenlight
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.
当您通过非const
引用传递指针时,您是在告诉编译器您将要修改该指针的值。您的代码不会这样做,但编译器认为会这样做,或者计划在将来这样做。
To fix this error, either declare x
constant
要修复此错误,请声明x
常量
// 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
:
或创建一个变量,nKByte
在调用之前为其分配一个指针test
:
float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);
回答by wilx
The &nKByte
creates a temporary value, which cannot be bound to a reference to non-const.
在&nKByte
创建一个临时值,它可以不被绑定到给非const的参考。
You could change void test(float *&x)
to void test(float * const &x)
or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);
.
您可以更改void test(float *&x)
为 ,void test(float * const &x)
或者您可以完全删除指针并使用void test(float &x); /*...*/ test(nKByte);
.
回答by Some programmer dude
When you call test
with &nKByte
, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.
当您调用test
with 时&nKByte
,address-of 运算符会创建一个临时值,您通常不能引用临时值,因为它们是临时的。
Either do not use a reference for the argument, or better yet don't use a pointer.
要么不要对参数使用引用,要么最好不要使用指针。