【问题标题】:Cannot convert argument from int * to const int *&无法将参数从 int * 转换为 const int *&
【发布时间】: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

标签: c++ pointers


【解决方案1】:

您不能这样做,因为您无法将引用到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

【讨论】:

    【解决方案2】:

    在主函数中将 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;
    }
    

    【讨论】:

    • 您能否解释一下为什么会这样,以获得完整的答案?
    • @Hayt 现在我看到您也在评论中提出了相同的解决方案。我的坏> :(
    • 我只是没有把它作为答案,因为当时我无法提出原因。如果您也为此添加解释也没关系。
    • 此功能现在不适用于int *。一个模板化的解决方案可以很好地概括这一点。
    【解决方案3】:

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

    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 int *。

    【讨论】:

      猜你喜欢
      • 2015-03-09
      • 1970-01-01
      • 2015-06-12
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 2016-11-11
      相关资源
      最近更新 更多