【发布时间】:2019-09-29 06:53:14
【问题描述】:
我对以下代码有两个问题,尤其是int sum(const int *begin, const int *end) 函数。我不明白的是,那个函数中的*p 和p 是什么?
*p 是该函数中的指针吗?p 呢? p 是变量吗?我读到的是:“在const int *p 中,*p(指向的内容)是恒定的,但p 不是恒定的。”
我不太明白这个函数中*p 和p 的区别。
我的第二个问题是:在int sum(...)的for循环中声明const在:const int *p = begin的原因是什么?是不是因为在int sum(...) 的签名中,有这个const 被声明为:const int *p = begin? IE。是不是因为 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;
}
【问题讨论】: