【问题标题】:Why can a function take (int *&) as a parameter? [duplicate]为什么函数可以将 (int *&) 作为参数? [复制]
【发布时间】:2019-04-18 07:54:40
【问题描述】:

以下是拆分数组的代码。
第一个输出数组将包含给定两个索引和第二个索引之间的输入数组条目 输出数组将包含其余条目。

void splitArray(int *arr, int size, int ind1, int ind2,
     int *&first, int &firstSize, int *&second, int &secondSize){
    firstSize = ind2 - ind1 + 1;
    secondSize = size - firstSize;
    first = new int[firstSize];
    second = new int[secondSize];
    for (int i = 0; i < ind1; i++)
    second[i] = arr[i];
    for (int i = ind1; i <= ind2; i++)
    first[i - ind1] = arr[i];
    for (int i = ind2 + 1; i < size; i++)
    second[i - firstSize] = arr[i];
    }

我可以理解为什么它有像 int *&amp;first 和 int *&amp;second 这样的参数,而不是它们与 int first 和 int second 相同,但在这段代码中它们被用作指向动态数组的指针。

【问题讨论】:

  • 不,它们不是 - int*&amp; 是对指向 int 的指针的引用。
  • 这里,&amp; 的意思是“这是一个 C++ 引用”,而不是“获取地址”。他们使用相同的符号表示两个不同的事物,它们之间的相关性仅比“按位与”的相关性稍高。
  • *&amp;first 将与 first 相同,如果它们是表达式并且 * 和 &amp; 是运算符,但这是一个声明,所以 * 和 &amp; 不是运算符但类型的一部分。

标签: c++ arrays pointers


【解决方案1】:

T *&amp;foo 声明对指向T 的指针的引用。不要将声明和定义中的 & 符号与地址操作符混淆。

如果被调用函数需要能够修改传递给它的指针的值,则使用对指针的引用:

void bar(int *&ptr) {
    ptr = 42;  // change the value of the pointer  (pseudo ... 42 is most likely
    *ptr = 42; // change the value of the pointee   not a valid pointer value)
}

// ...

int *foo = nullptr;
bar(foo);
// foo == 42;

提示:从右到左读取类型:T *&amp; --> &amp;* T --> 引用 (&amp;) 到指针 (*) 以键入 T。

【讨论】:

    猜你喜欢
    • 2020-07-03
    • 2017-08-24
    • 1970-01-01
    • 2019-02-27
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    相关资源
    最近更新 更多