我知道const T*&是指向常量类型T的指针引用。该指针具有低级const,因此它不会改变其指向的值。然而,以下代码在编译时失败,并给出以下消息:
error C2664: 'void pointer_swap(const int *&,const int *&)': cannot convert argument 1 from 'int *' to 'const int *&'.
有没有一种方法可以在函数中修改指针但防止指向的值发生变化?
void pointer_swap(const int *&pi, const int *&pj)
{
const int *ptemp = pi;
pi = pj;
pj = ptemp;
}
int main()
{
int i = 1, j = 2;
int *pi = &i, *pj = &j;
pointer_swap(pi, pj);
return 0;
}
int*
,需要一个const int*
作为输入。将 pi 和 pj 更改为const int*
可以解决错误。但我不确定为什么没有从非 const 到 const 的隐式转换。 - Haytpi = &something_that_really_is_const;
的操作,这将允许调用者修改something_that_really_is_const
。 - Oliver Charlesworth