【问题标题】:C/C++ convention for pointers and `const`指针和 `const` 的 C/C++ 约定
【发布时间】:2016-09-14 06:20:03
【问题描述】:

我在维基百科上阅读了this(也粘贴在下面):

遵循通常的 C 声明约定,声明遵循使用,并且指针中的 * 写在指针上,表示取消引用。例如,在声明 int *ptr 中,解引用形式 *ptr 是一个 int,而引用形式 ptr 是一个指向 int 的指针。 因此 const 将名称修改到其右侧。相反,C++ 约定是将 * 与类型相关联,如 int* ptr 中,并将 const 读取为修改左侧的类型。因此 int const * ptrToConst 可以读作“*ptrToConst is a int const”(值是常量),或“ptrToConst is a int const *”(指针是指向常量整数的指针)。

我真的无法得到满意的解释:

  • 在什么意义上修改?

  • nametype 的用途是什么(参见上面的链接)?

  • 为什么要在const的右边?

【问题讨论】:

  • 那个链接没有任何用处。
  • 我刚刚修复了链接。
  • 那个维基百科部分很混乱。如果例子是const int *ptrToConst;const int * const constPtrToConst;,这里引用的句子会更有意义
  • 看看这个你就明白了:stackoverflow.com/questions/1143262/…
  • 是的,我认为它很模棱两可。我确实在那篇文章的维基“谈话”标签中写了一些注释。该链接澄清了我的正确含义:左/右意味着“*标记”(维基百科文本恕我直言至少无法解读)。所以 name == pointer, type == pointee.

标签: c++ c


【解决方案1】:

constvolatilerestrict(C99 及更高版本)关键字被视为类型限定符。它们是类型签名的组成部分,并描述了有关类型的附加语义。

如果它们出现在声明的最顶层,它们会影响声明的标识符:

const int a = 5; // prevents modifications of "a"
int *const p = &x; // prevents modifications of "p", but not "*p"
int **const q = &y; // prevents modifications of "q", but not "*q" and "**q"

如果它们出现在指针子类型中(在星号之前),它们会影响特定取消引用级别的指向值:

const int *p = &x; // prevents modifications of "*p", but not "p"
const int **q = &y; // prevents modifications of "**q", but not "*q" and "q"
const int *const *r = &z; // prevents modifications of "**r" and "*r", but not "r"
const int *const *const s = &a; // prevents modifications of "**s", "*s" and "s"

维基百科摘录讨论了声明指针的两种不同约定:

int *p; // more common in C programming
int* p; // more common in C++ programming

我会说“真正的”约定是第一个,因为它根据语言的语法工作(声明镜像使用)。该声明中的星号实际上与您在普通表达式中的指针上使用的解引用运算符相同。因此在p(指针本身)上应用*(间接)后返回int类型。

还要注意,类型限定符相对于类型说明符和其他类型限定符的顺序并不重要,因此这些声明是等价的:

const int a; // preferred
int const a; // same, not preferred

const volatile int b; // preferred
volatile const int b; // same, not preferred
volatile int const b; // same, not preferred

const int *p; // preferred
int const *p; // same, not preferred

【讨论】:

    【解决方案2】:

    它在什么意义上修改?

    在使其保持不变的意义上进行修改,这意味着它不能被修改(分配给或传递给可能修改它的函数)。

    名称与类型的含义是什么(参见上面的链接)?

    我认为这里的名称是源代码中写的单词。

    为什么要在 const 的右边?

    “将名称向右修改”的意思是,例如:

    const char * str,这里const修改了char,也就是说字符是常量,不能修改。你可以让 str 指向一个新的字符,但你仍然不能修改它(至少不能通过 str)。 *str = 'a'; 是编译器错误,str = "foo"; 是好的。

    char * const str,这里const修改了str,也就是说str的值是不能修改的。它指向某个char,你可以通过str修改那个char,但不能让str指向另一个char。 *str = 'a'; 现在可以了,str = "foo"; 是错误的。

    【讨论】:

    • 非常感谢你们。我正在通过维基百科的引用部分来疯了。我在其他 Stackoverf 的帮助下正确推断出一些事实。线程..但大多数(例如左/右)我真的没有。感谢用户,特别感谢 Shankar 的 cmets。这两个答案也很好:我会将所有两个回复都标记为答案。我不能,所以我先按时间顺序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 2011-03-11
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多