使用指针,我可以做到这一点:
int a=1;
int b=2;
const int* cnstIntPtr = &a;
// (*cnstIntPtr)++ does not work, makes sense since value pointed to is constant
cnstIntPtr = &b; // works, makes sense
const int* const cnstIntCnstPtr = &a;
// (*cnstIntCnstPtr)++; does not work, makes sense since value pointed to is constant
// cnstIntCnstPtr = &b; does not work, makes sense since pointer is constant
但需要提供参考资料:
const int& cnstIntRef = a;
// cnstIntRef++; does not work, makes sense since const refers to value at address
// cnstIntRef = b; why does this not work? "expression must be modifiable lvalue"
const int& const cnstIntCnstRef = a;
//cnstIntCnstRef++; does not work, makes sense since const refers to value at address
//cnstIntCnstRef = b; does not work, makes sense since const refers to value at address
为什么当const应该引用地址上的值时(类比指针的工作方式),我不能重新分配给const引用。如果一般情况下不可能,为什么会这样,并且
const int& const cnstIntCnstRef
中第二个const的含义是什么?
const int& const cnstIntCnstRef
中的第二个const
是多余的。 - Igor Tandetnikstd::reference_wrapper
。请注意,它主要用于通用代码和转发目的。 - Guillaume Racicot