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);
这篇关于对非常量的引用的初始值必须是左值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对非常量的引用的初始值必须是左值
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
