【发布时间】:2019-09-29 17:14:21
【问题描述】:
我对以下代码有两个问题,尤其是int sum(const int *begin, const int *end) 函数。我不明白的是为什么我们将p 分配为指向不可变常量的指针,即开始。但是,在sum() 内的for 循环中也有++p?为什么是++p 而不是++*p?为什么是p!=end 而不是*p!= end?
我读到的是:“在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;
}
【问题讨论】:
-
你是从什么来源学习 C++ 的?
-
p是一个包含地址的指针。*p是存储在该地址中的值。指针由int *p;声明。++p增加地址。++*p增加值。 -
正如您已经提到的,
const int *p将指向一个 const int,这意味着我们只能移动指针而不能更改指向的值。函数 sum 应该只计算给定范围内的总和,并且不应该改变数组的值,因此const int*用于确保这一点。 -
你好,但是我可以知道在这种情况下增加地址是什么意思吗?因为不是地址像 0x321F ... 或类似的东西吗?在这里将地址增加 1 是什么意思?喜欢++p?所以 0x321F +1 ?然后再 +1?
-
如果
p是指向数组a中元素i的指针,那么p+1是指向a[i+1]的指针(即递增它使其指向下一个元素)。