【发布时间】:2016-09-06 09:54:25
【问题描述】:
我明白 const T*& 是指向 const 类型 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*可以修复错误。我不确定为什么没有从非常量到常量的隐式转换。 -
@Hayt - 因为引用。它将允许函数执行
pi = &something_that_really_is_const;之类的操作,然后允许调用者修改something_that_really_is_const。