对非常量的引用的初始值必须是左值
我正在尝试使用引用指针将值发送到函数中,但它给了我一个完全不明显的错误
#include "stdafx.h";#include 使用命名空间标准;无效测试(浮动 *&x){* x = 1000;}int main(){浮动 nKBy??te = 100.0;测试(&nKByte);cout<<nKByte<<"兆字节"<<结束;cin.get();}
<块引用>
错误:对非常量引用的初始值必须是左值
我不知道我必须怎么做才能修复上述代码,有人能给我一些关于如何修复该代码的想法吗?
解决方案当您通过非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);
相关文章