有关此函数中参数的问题

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

我对以下代码有两个问题,特别是int sum(const int *begin, const int *end)函数。我不明白的是,那个函数中的*pp是什么?

*p是该函数中的指针,p又如何? p是变量吗?我在读:“ const int *p中,*p(指向的内容)是常数,但是p不是常数。

我不太了解此功能中*pp之间的区别。

[我的第二个问题是:在const的for循环中的const int *p = begin中声明int sum(...)的原因是什么?是因为在int sum(...)的签名中声明了constconst int *p = begin吗?即是因为begin被声明为不可变的东西-这就是为什么在for循环中,我们必须声明begin是指针*p指向的不可变常量?

/* Function to compute the sum of a range of an array (SumArrayRange.cpp) */
#include <iostream>
using namespace std;

// Function prototype
int sum(const int *begin, const int *end);

// Test Driver
   int main() {
   int a[] = {8, 4, 5, 3, 2, 1, 4, 8};
   cout << sum(a, a+8) << endl;        // a[0] to a[7]
   cout << sum(a+2, a+5) << endl;      // a[2] to a[4]
   cout << sum(&a[2], &a[5]) << endl;  // a[2] to a[4]
}

// Function definition
// Return the sum of the given array of the range from
// begin to end, exclude end.
int sum(const int *begin, const int *end) {
    int sum = 0;
    for (const int *p = begin; p != end; ++p) {
        sum += *p;
    }
    return sum;
}
c++ pointers const
1个回答
0
投票

p是指针变量。 *有两个含义:

  1. 这是指针声明
  2. 将其运算符应用于p变量以获取其值
const int* p; // (1) p is pointer on immutable int
int x = *p; // (2) let's take value where p points and put it in x
*p = 1; // (2) set value where p points

[是的,您对p的const是正确的。这是因为beginconst

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