首页 > 解决方案 > 指向常量值的 const 指针示例

问题描述

我知道在 c++ 中我们可以有一个指向常量值的常量指针:

const int value{ 5 };
const int* const ptr{ &value };

这表示:

这样的指针什么时候有用?

标签: c++pointers

解决方案


例如,您可以在使用指针迭代时存储数组结束后的位置。这对于避免在比下面的更复杂的循环中意外修改指针很有用。如果除此之外您不希望数组是可修改的,您还将使元素类型为 const;这导致指向 const 元素的 const 指针很有用:

void printArray(int const* array, size_t count)
{
    int const* pos = array;
    int const* const end = array + count; // end is the pointer past the count-th element of array

    while(pos != end)
    {
        std::cout << *pos << std::endl;
        ++pos;
    }
}

推荐阅读