Const之前或之后的类型?

时间:2013-12-18 11:11:58

标签: c++

我有以下代码:

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

不应该是:

const string&

3 个答案:

答案 0 :(得分:17)

const之类的Cv限定符适用于它们左边的任何内容,除非没有任何内容,在这种情况下它们适用于右边。对于string const&const适用于其左侧的string。对于const string&const适用于其右侧的string。也就是说,它们都是对const string的引用,因此在这种情况下,它没有任何区别。

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

答案 1 :(得分:5)

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.

答案 2 :(得分:3)

它在该环境中的任何一种方式都有效,并且是个人偏好和编码惯例的问题。

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

string * const ptr;

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

class Foo
{
    void func() const;
};