【问题标题】:Const pointer C++ Stroustrup [duplicate]常量指针 C++ Stroustrup [重复]
【发布时间】:2018-09-24 01:15:30
【问题描述】:
int count_x(const char* p, char x)
     // count the number of occurrences of x in p[]
     // p is assumed to point to a zero-terminated array of char (or to nothing)
{
     if (p==nullptr)
           return 0;
     int count = 0;
     for (; *p!=0; ++p)
           if (*p==x)
                 ++count;
     return count;
}

p 是一个指针。 const 意味着指针不能被修改。但是在for循环中,有++p,这意味着指针被迭代/递增以访问值*p

那里有一个矛盾 - p 不能被修改,但它正在递增/修改?

【问题讨论】:

  • 不,const 表示无法修改事物指针。您仍然可以更改指针。
  • 那个 const 意味着 p 指向的是 const,而不是 p 本身。对于您所描述的内容,const 需要位于 * 的另一侧。
  • @mrunion 不,它没有。
  • 我想知道你为什么觉得有必要在你的问题中包含 Stroustrup 的名字..
  • @user3738870 代码来自 Stroustrup 的 A Tour of C++

标签: c++ pointers constants


【解决方案1】:

C++ 中的声明是从右到左读取的。所以像

const char* p

将读取:p 是指向 const char 的非常量指针。

显然,p 不是const,但它指向的是const。所以*p = 's' 是非法的,但p++ 不是。

【讨论】:

  • 如果这就是该行的意思, (const char)* p 会不会更有意义?那么如何将指针本身声明为 const 呢?
  • @user3180 char *const p.
猜你喜欢
  • 2012-09-14
  • 2023-04-07
  • 2014-02-23
  • 2011-08-27
  • 1970-01-01
  • 2012-04-22
  • 1970-01-01
  • 2021-10-02
  • 2021-04-19
相关资源
最近更新 更多