const reference

#include <iostream>
using std::cout;
using std::endl;
intmain()
{
int ival = 0;
const int ival3 = 1;

int * const & ref = &ival;

// int * & ref2 = &ival; // error, because &ival is of type const, and a reference of type const is a const reference
int * const & ref2 = &ival;

 int * const & ref1 = &ival3; // error because ival3 is of type const int,
 //error: invalid conversion from 'const int*' to 'int*' [-fpermissive]
 
const int * const & ref4 = &ival3;

return 0;
}
  •  error: invalid conversion from 'const int*' to 'int*' ,int* 是指 int * const & ref1 , const int * 是指 const int ival3
  • The compiler thinks it is binding an lvalue to an rvalue
#include <iostream>
using std::cout;
using std::endl;
intmain()
{
int * ival = 0;
const int ival3 = 1;

int * const & ref = ival;

ival ++;


// int * & ref2 = &ival; // error, because &ival is of type const, and a reference of type const is a const reference
const int * const & ref2 = ival;
ival ++;
*ref2 = 0;//assignment of read-only location '*(const int*)ref2'

 //int * const & ref1 = &ival3; // wrong because ival3 is of type const int,
 //error: invalid conversion from 'const int*' to 'int*' [-fpermissive]
 
//const int * const & ref4 = &ival3;

return 0;
}

 

Guess you like

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