const reference keyword example code


#include <iostream>
using std::cout;
using std::endl;

intmain()
{
	int i = 5;
    const int ic =10;
    const int *pic = &i;//Define from right to left "pic is a pointer to an int type that is defined as a const object"
    i = i+1;
    pic = pic + 1;
   // *pic = 2; Error *pic cannot be an lvalue
    const int *pic_1 = ⁣
    pic_1 = pic_1 + 1;
    
    const int * const pic_2 = ⁣ //pic_2 is a pointer to a const int type defined as a const object
    i = i + 1;
   // pic_2 = pic_2 + 1;// error assignment of read-only variable 'pic_3'
   // *pic_2 = 2; //Error *pic_2 cannot be an lvalue
    
    const int * const pic_3 = &i;
    i = i+1;
   // pic_3 = pic_3 + 1; error assignment of read-only variable 'pic_3'
    //*pic_3 = 2; //Error *pic_2 cannot be an lvalue
    
 // int * const cpi = ⁣ // cpi is a pointer to a const int, defined as a non-const object
   
   int * const cpi_1 = &i; //cpi_1 is a pointer to a const int type, which is defined as a non-const object
    * cpi_1 = 10;
   // cpi = cpi + 1;
    
	return 0;
}  //End of main




#include <iostream>
using std::cout;
using std::endl;

intmain()
{
	int ival = 0;
    const int ival3 = 1;
    const int &rval1 = 1.01;
    int &rval2 = ival;
    int * const &rval3 = &ival;
    int *pi = &ival;
    int * &rval4 = pi;
    int &rval5 = *pi;
    
    //int &* prval1 = pi;//error: cannot declare pointer to 'int&'
    int * & prval1 = pi;//right
    
    const int & ival2 = 1;
    
    //const int * & prval2 = &ival3;//error: cannot bind non-const lvalue reference of type 'const int*&' to an rvalue of type 'const int*'
    const int * const & prval2 = &ival3;
    
    //int * & prval3 = &ival;//error: cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*'
    const int * & prval3 = &ival;//error: cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*'
    //const int * const & prval3 = &ival1;
	return 0;
}  //End of main


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326406495&siteId=291194637