2016-09-06 54 views
3

我不明白,常量T * &是指针为const类型T的引用指针低级别的常量,这样它不会改变的价值指向至。但是,下面的代码失败在编译时并给出了以下消息:不能从int *转换参数const int的*

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

你有一个'INT *'而且需要'const int的*'作为输入。所以把pi和pj改为'const int *'可以修复错误。我不知道为什么没有从非const到const的隐式转换。 – Hayt

+1

@Hayt - 由于参考。这将允许函数来执行类似'PI = something_that_really_is_const;',那么这将允许呼叫者修改'something_that_really_is_const'。 –

+0

啊有道理。谢谢:) – Hayt

回答

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

你还可以解释为什么这是这种情况,为了一个完整的答案? – Hayt

+0

@Hayt现在我看到你在评论中也提出了同样的解决方案。我的坏> :( –

+0

我只是没有把它作为一个答案,因为我不能拿出一个为什么在这一点上,如果你这一点。 – Hayt

3

你不能这样做,因为你不能绑定参考-TO-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 

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 &. 

两个例子表明,编译器会帮助我们,使从电流型转换为const电流型。因为我们告诉编译器参数是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到你希望没有发生,因为该函数的声明只是说我想非const &常量的隐式转换,它的类型是const int *。

相关问题