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

Cannot convert argument from int * to const int *&

本文关键字:int const 转换 参数      更新时间:2023-10-16

我确实理解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;
}

您不能这样做,因为您不能将指向- const的引用绑定到指向非- const的引用。*

您可以使用自己的

,但使用std::swap更有意义,它是专门为此目的而设计的,并且是完全通用的:

#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

使PI和pj在main函数中为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;
}

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

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的转换。因为我们告诉编译器参数是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 &,它的类型是const int *。