我对以下代码有两个问题,特别是int sum(const int *begin, const int *end)
函数。我不明白的是,那个函数中的*p
和p
是什么?
*p
是该函数中的指针,p
又如何? p
是变量吗?我在读:“ 在const int *p
中,*p
(指向的内容)是常数,但是p
不是常数。”
我不太了解此功能中*p
和p
之间的区别。
[我的第二个问题是:在const
的for循环中的const int *p = begin
中声明int sum(...)
的原因是什么?是因为在int sum(...)
的签名中声明了const
的const 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;
}
p
是指针变量。 *
有两个含义:
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
是正确的。这是因为begin
是const