C++ initial value of reference to non-const must be an lvalue

后端 未结 3 2033
逝去的感伤
逝去的感伤 2020-12-07 18:59

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 

        
相关标签:
3条回答
  • 2020-12-07 19:18

    The &nKByte creates a temporary value, which cannot be bound to a reference to non-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);.

    0 讨论(0)
  • 2020-12-07 19:27

    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.

    Either do not use a reference for the argument, or better yet don't use a pointer.

    0 讨论(0)
  • 2020-12-07 19:33

    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);
    
    0 讨论(0)
提交回复
热议问题