initial value of reference to non-const must be an lvalue(对非常量的引用的初始值必须是左值)
问题描述
我正在尝试使用引用指针将值发送到函数中,但它给了我一个完全不明显的错误
#include "stdafx.h";#include 使用命名空间标准;无效测试(浮动 *&x){* x = 1000;}int main(){浮动 nKByte = 100.0;测试(&nKByte);cout<<nKByte<<"兆字节"<<结束;cin.get();}
<块引用>
错误:对非常量引用的初始值必须是左值
我不知道我必须怎么做才能修复上述代码,有人能给我一些关于如何修复该代码的想法吗?
当您通过非const
引用传递指针时,您是在告诉编译器您将要修改该指针的值.您的代码不会这样做,但编译器认为会这样做,或者计划在将来这样做.
要修复此错误,请声明 x
常量
//这告诉编译器你不打算修改指针//通过引用传递无效测试(浮动*常量&x){* x = 1000;}
或者创建一个变量,在调用test
之前将指针分配给nKByte
:
float nKByte = 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);
这篇关于对非常量的引用的初始值必须是左值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对非常量的引用的初始值必须是左值
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01