我有以下代码:
string const& operator[] (size_t index) const { return elems[index]; }
不应该是:
const string&
答案 0 :(得分:17)
const
之类的Cv限定符适用于它们左边的任何内容,除非没有任何内容,在这种情况下它们适用于右边。对于string const&
,const
适用于其左侧的string
。对于const string&
,const
适用于其右侧的string
。也就是说,它们都是对const
string
的引用,因此在这种情况下,它没有任何区别。
有些人喜欢在左边(如const int
),因为它从左到右阅读。有些人喜欢在右侧(例如int const
)使用它以避免使用特殊情况(例如int const * const
比const 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;
};