zoukankan      html  css  js  c++  java
  • C++ Error : initial value of reference to non-const must be an lvalue

    如下这段代码,编译报错:

    Error : initial value of reference to non-const must be an lvalue

    #include <iostream>
    using namespace std;
    void test(float *&x){
        *x = 1000;
    }
    int main(){
        float nKByte = 100.0;
        test(&nKByte);
        cout << nKByte << " megabytes" << endl;
    }
    

      

    原因为test函数的参数是个引用, 你有可能修改这个引用本身的值(不是引用指向的那个值),这是不允许的。

    所以一个修复办法为声明引用为const,这样你告诉编译器你不会修改引用本身的值(当然你可以修改引用指向的那个值)

    修改版1:

    void test(float * const &x){
        *x = 1000;
    }
    

    另一个更简单的修改办法是直接传递指针,

    修改版2:

    void test(float * x){
        *x = 1000;
    }
    

      

    reference:

    http://stackoverflow.com/questions/17771406/c-initial-value-of-reference-to-non-const-must-be-an-lvalue

  • 相关阅读:
    from import 的认识
    模块初识
    eq方法
    hash介绍
    item系列
    析构函数
    serializers进阶
    APIView源码解析
    RPC协议
    面试题补充
  • 原文地址:https://www.cnblogs.com/plwang1990/p/4141936.html
Copyright © 2011-2022 走看看