gpt4 book ai didi

c++ - 通过函数中的引用将 const 指针传递给 const

转载 作者:行者123 更新时间:2023-12-02 09:50:29 25 4
gpt4 key购买 nike

我正在玩一些数组并通过引用函数来传递指针。以下面的代码为例:

#include<iostream>

void test_fn(const int* const &i){
std::cout<<*i<<std::endl;
}

int main(){
int arr_1[5] {1, 3, 6, 4, 5};
int *int_ptr1 {nullptr};
int_ptr1=arr_1;
test_fn(int_ptr1);

return 0;
}

此代码运行正常。

但是,如果我修改 test_fn 的定义读书:

void test_fn(const int* &i){
std::cout<<*i<<std::endl;
}

我收到以下错误:

cannot bind non-const lvalue reference of type 'const int*&' to an rvalue of type 'const int*'



我的问题是:为什么这是第二个示例中的问题,而不是第一个示例中的问题,唯一的区别是指针作为 const 指针传递?

最佳答案

在第二个例子中,函数引用了 非常量 const int*指针,但你给它一个 int*而是指针。因为指针是非常量的,所以引用不能绑定(bind)到临时 const int*编译器创建的变量,用于从 int* 隐式转换至const int* .引用需要非常量 const int*调用站点的变量,因此您必须显式声明 int_ptr1const int*而不是 int* :

const int *int_ptr1 = arr_1;

在第一个示例中,函数引用了 常量 const int*指针。由于指针是 const,编译器可以隐式转换 int*const int*并将结果存储在临时变量中,然后将引用绑定(bind)到该临时变量。

关于c++ - 通过函数中的引用将 const 指针传递给 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59972823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com