无法将参数从int *转换为const int *& [英] Cannot convert argument from int * to const int *&

查看:771
本文介绍了无法将参数从int *转换为const int *&的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实了解const T *&是对const类型T的指针的引用.该指针具有低级const,因此它不会更改其指向的值.但是,以下代码在编译时失败,并给出以下消息:

I do understand that const T*& is a reference of pointer to const type T. The pointer has low-level const so that it won't change the value it points to. However, the following code fails at compile time and gives the following message:

error C2664: 'void pointer_swap(const int *&,const int *&)': cannot convert argument 1 from 'int *' to 'const int *&'.

有什么方法可以修改指针,但可以防止指向的值在函数中更改?

Is there any way to modify the pointer but prevent the pointed to value from changing in the function?

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;
}

推荐答案

您无法执行此操作,因为您无法将对const的引用绑定到对非const的引用. sup> *

You can't do this because you can't bind a reference-to-const to a reference-to-non-const.*

您可以自己动手,但仅使用 std::swap ,它是为此目的而明确设计的,并且是完全通用的:

You could roll your own, but it makes more sense to just use std::swap, which is designed explicitly for this purpose, and fully generic:

#include <algorithm>

std::swap(pi, pj);

[ 在线示例 ]

*因为这将允许这样的事情:

int       *p = something_non_const();
const int *q = something_really_const();
const int *&r = p;
r = q;     // Makes p == q
*p = ...;  // Uh-oh

这篇关于无法将参数从int *转换为const int *&amp;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆