引用const作为函数参数的指针

问题描述 投票:2回答:1

我有以下基本代码:

基本代码

int main()
{
  int i = 1;

  const int* p = &i;
  int* q = &i;

  test_ptr(p);
  test_ptr(q);
}

谁能解释为什么第一个和第三个示例可以使用上述基本代码,而第二个则不能?

示例实现test_ptr()

示例1起作用。之所以可行,是因为带有指向const int指针的函数也将接受指向非const int的指针(但反之亦然)]

void test_ptr(const int* p)  // pointer to const int
{

}

示例2不起作用。我真的不明白为什么。它仍然是const int的指针,但作为引用传递。这与我对引用如何工作的理解不一致。当我将非常量指针传递给该函数时,它将失败。

void test_ptr(const int*& p)  // reference to pointer to const int
{

}

示例3再次起作用,我完全迷失了。因此,如果情况2不起作用,那么如果我将int *表示为typedef,为什么它又可以工作?

typedef int* int_ptr;

void test_ptr(const int_ptr& p)  // like case 2 but int* expressed as typedef
{

}

当我使用指针到指针而不是引用到指针时,也会发生这种情况。

Edit:

示例3需要一个不同的main函数来使用typedef:
int main()
{
  int i = 1;

  const int_ptr p = &i;  // use typedef here
  int_ptr q = &i;  // use typedef here

  test_ptr(p);
  test_ptr(q);
}

我有以下基本代码:基本代码int main(){int i = 1; const int * p =&i; int * q =&i; test_ptr(p); test_ptr(q); }谁能解释为什么第一个和第三个示例...

c++ pointers reference arguments const
1个回答
1
投票

示例2:

© www.soinside.com 2019 - 2024. All rights reserved.