无法将参数从 int * 转换为 const int *&
Cannot convert argument from int * to const int *&
我确实理解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 *。
相关文章:
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 在C++中,如果"int a = 3; int* p = &a;",那么为什么不允许"const int* &pp = p",但允许"const int* const &pp = p"?
- 调用'myStud::myStud(int, const char [5], int, int, int)'没有匹配函数
- 返回对象时从'const DList<int>* const'到 'DList<int>*' [-fallowive] 的转换无效
- int(int)& 或 int(int) const &是什么类型?
- 传递 const int* 和 int* 时调用重载函数的不同版本(const int* const&/&&)
- 如何在构造函数中初始化int const * const
- 对"displayForStudent(int, int const*, double const*, int)"的未定义引用 collect2.exe:错误:ld 返回 1 个退出状态
- 如何在 C++ 中解释"const int *const & variable"
- 为什么"int & const" MSVC 编译得很好?
- const int const&和const int&in C++有什么区别?
- std::set<int * const> 不会编译
- " invalid operands of types 'int' and 'int* const'" 来自功能的错误,来自书
- std::initializer_list<int const> 不能从 std::initializer_list <int>构造
- 对'std::string Helper::ToString<int>(int const&)'的未定义引用
- 无法弄清楚 int[3][3] 和 int(* const)[3] 之间的区别
- const int* const fun(const int* const& p) const的含义;
- 为什么vector<int * const>是非法/不合逻辑的?
- 对 Stack<int>::p ush(int const&) 的未定义引用
- JsonCpp:未定义的对"Json::Value::operator[](int) const"的引用