无法将参数从int *转换为const int *&

时间:2016-09-06 09:54:26

标签: c++ pointers

我明白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;
}

3 个答案:

答案 0 :(得分:3)

您无法执行此操作,因为您无法将引用 - const绑定到引用到非 - const *

你可以自己动手,但仅使用明确为此目的设计的std::swap更有意义,并且完全通用:

#include <algorithm>

std::swap(pi, pj);

[ Live example

*因为这可以允许这样的事情:

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

答案 1 :(得分:0)

在主函数中将pi和pj设为const。

#include <iostream>
using namespace std;

void pointer_swap(const int *&pi, const int *&pj)
{
    const int *ptemp = pi;
    pi = pj;
    pj = ptemp;
}

int main()                                                                
{                                    
    int i = 1, j = 2;                
    const int *pi = &i, *pj = &j;          
    pointer_swap(pi, pj);
    return 0;
}

答案 2 :(得分:0)

这是我的想法。希望能帮到你。

void fun1(const int * p) 
{
}

int * pa = 0;
fun1(pa); //there is implicit conversion from int * to const int *

void fun2(const int & p)
{

}
int a = 0;
fun2(a); //there is implicit conversion from int & to const int &.

这两个例子都表明编译器将帮助我们从current-type转换为const current-type。因为我们告诉编译器param是const。

现在,看看这个:

void fun3(const int * &p) 
{
//this declaration only states that i want non-const &, it's type is const int * .
}

int *pi = 0;
fun3(pi); // error C2664

由于函数声明只表明我想要非const&amp;,它的类型是const int *。