【问题标题】:Const before or after the type? [duplicate]const 在类型之前还是之后? [复制]
【发布时间】:2014-01-06 12:52:37
【问题描述】:

我有以下代码:

string const& operator[] (size_t index) const { return elems[index]; }

不应该是:

const string&

?

【问题讨论】:

  • 这里没有区别。
  • 以最纯粹的形式,它应该紧随其后以保持一致。事实上,它可以在左边走是个例外,真的。也就是说,我个人更喜欢左。
  • 我觉得把类型名放在右边会更容易看懂,不过没什么区别。
  • 在第一种情况下,从“从右到左”读取类型“对 const 字符串的引用”。有些人主张总是使用从右到左的符号,因为这样我们就有了一致性。我倾向于支持这个想法,但可能不会被发现守在路障上。

标签: c++


【解决方案1】:

const 这样的Cv 限定符适用于它们左边的任何东西,除非什么都没有,在这种情况下它们适用于右边。对于string const&const 适用于其左侧的string。对于const string&const 适用于其右侧的string。也就是说,它们都是对conststring 的引用,所以在这种情况下,没有区别。

有些人喜欢把它放在左边(比如const int),因为它从左到右读取。有些人喜欢把它放在右边(比如int const)以避免使用特殊情况(例如int const * constconst int* const更一致)。

【讨论】:

  • 什么是const int* constint const * const....?
  • @user2745266 它们都是const 指向const int 的指针。
  • 感谢您的回复。我想问的是const 在这两种情况下如何应用(哪一种用于 int,哪一种用于指针)。也许我应该以适当的方式问。谢谢。
  • @user2745266 正如我在回答开头所描述的那样,consts 适用于它们左侧的任何内容,除非没有任何内容,在这种情况下它们适用于右侧。因此,两者中的第一个const 适用于int,第二个const 适用于*
  • const 系统地放在右侧的真正论据是当涉及到 typedef 时:给定typedef int* pInt;const pInt v;pInt const v; 都表示相同的东西:int* const。然而,这并不是大多数人一开始所期望的。
【解决方案2】:

const 可以位于数据类型的任一侧,因此:

const int *”等同于“int const *

const int * const”与“int const * const”相同

int *ptr;           // ptr is pointer to int
int const *ptr;     // ptr is pointer to const int
int * const ptr;        // ptr is const pointer to int
int const * const ptr;  // ptr is const pointer to const int
int ** const ptr;       // ptr is const pointer to a pointer to an int
int * const *ptr;       // ptr is pointer to a const pointer to an int
int const **ptr;        // ptr is pointer to a pointer to a const int
int * const * const ptr;    // ptr is const pointer to a const pointer to an int

基本规则是const applies to the thing left of it. If there is nothing on the left then it applies to the thing right of it.

【讨论】:

    【解决方案3】:

    在这种情况下,无论哪种方式都可以,这取决于个人喜好和编码约定。

    一些程序员更喜欢将它放在类型名称之后,以便与const 的其他用法更加一致。例如,如果您要声明一个指针本身(而不是指向的类型)为const 的指针,则需要将其放在星号之后:

    string * const ptr;
    

    同样,如果你要声明一个const 成员函数,它需要在函数声明之后;例如:

    class Foo
    {
        void func() const;
    };
    

    【讨论】:

      猜你喜欢
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 2012-11-03
      相关资源
      最近更新 更多