reference variable

后端 未结 3 1126
感情败类
感情败类 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: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;
    

提交回复
热议问题