reference variable

后端 未结 3 1122
感情败类
感情败类 2021-01-19 16:13

In some text it is given that we can\'t assign constant values to a reference variable. When I executed such a program I could do it. Is there any condition we can\'t assign

相关标签:
3条回答
  • 2021-01-19 16:51

    You can initialize a constant reference to a constant value.

    const int &i = 12;
    

    If the reference is not const, you get a compiler error.

    int &i = 12; //compiler error
    

    Constant values (e.g. literals) are (most of the time) stored in read-only segments of the memory. Consequently, you can't reference them using non-const references, because that would mean you could modify them.

    0 讨论(0)
  • 2021-01-19 16:53

    You cannot assign a constant value to a non-constant reference, the same way you could not assign a constant value's address to a pointer pointing to a non-constant value.

    At least, not without a const_cast.

    Edit: If you were actually referring to literal values, Luc's answer is the better one. I was referring to const variables, not literals.

    0 讨论(0)
  • 2021-01-19 16:57

    You may be a bit confused regarding the difference between "initialisation" and "assignment". These are different in C++ and understanding the difference is crucial to understanding the language. Ignoring references:

    int x = 1;    // initialisation
    x = 1;        // assignment
    

    References can only be initialised

    int & r = x;  // initialisation
    r = 2;        // assigns 2 to x _not_ to r
    

    There is no way of re-initialising a reference.

    Regarding your question, as far as consts are concerned, you can initialise const reference with a const value:

    const int & r2 = 42;
    
    0 讨论(0)
提交回复
热议问题