What is definition of reference type?

前端 未结 4 2290
攒了一身酷
攒了一身酷 2020-12-30 17:12

How do you define (explain) in a formal and strict way what is reference type in C++?

I tried to google, and looked into Stroustrup\'s \"The C++ Programming Language

4条回答
  •  既然无缘
    2020-12-30 17:38

    A major difference between C and C++ (other than Objects and Classes!) is references. A reference is like a const pointer to a variable. Assigning a reference is a bit like using a pointer but with & not * and you don't need to difference. The difference is that you assign an address to a pointer but a variable to a reference variable. The line below suggests that the value of a is copied into aref. But it is not, instead aref is a reference to the variable a. Once assigned, aref is the same as a. Any changes to aref are changes to a as example below shows

    int & aref = a;

     #include 
     #include "stdafx.h"
    
      int main()
       {
          int a=9;
          int & aref = a;
          a++;
          cout << "The value of a is %i\n" << aref;
          return 0;
        }
    

    Also remember that

    1. A reference must always refer to something.NULLs are not allowed.

    2. A reference must be initialized when it is created. An unassigned reference can not exist.

    3. Once initialized, it cannot be changed to another variable.

    If it help you please inform me, thanx

提交回复
热议问题