const reference 关键字 示例 代码


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

int main()
{
	int i = 5;
    const int ic =10;
    const int *pic = &i;//从右往左定义“pic 是一个指向int类型的、被定义成const对象的指针”
    i = i+1;
    pic = pic + 1;
   // *pic = 2; Error  *pic 不能做左值
    const int *pic_1 = &ic;
    pic_1 = pic_1 + 1;
    
    const int * const pic_2 = &ic; //pic_2 是一个指向const int类型的、被定义成const对象的指针
    i = i + 1;
   // pic_2 = pic_2 + 1;// error assignment of read-only variable 'pic_3'
   // *pic_2 = 2; //Error  *pic_2 不能做左值
    
    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 不能做左值
    
 //  int * const cpi = &ic; // cpi是一个指向 const int类型,被定义为非const对象的指针
   
   int * const cpi_1 = &i; //cpi_1是一个指向const int 类型,被定义为非const对象的指针
    *cpi_1 = 10;
   // cpi = cpi + 1;
    
	return 0;
}  //End of main




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

int main()
{
	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


猜你喜欢

转载自javaeye-hanlingbo.iteye.com/blog/2408354