类型之前或之后的常量
Const before or after the type?
我有以下代码:
string const& operator[] (size_t index) const { return elems[index]; }
不应该是:
const string&
?
像const
这样的 Cv 限定符适用于它们左侧的任何内容,除非什么都没有,在这种情况下,它们适用于右侧。对于string const&
,const
适用于其左侧的string
。对于const string&
,const
适用于其右侧的string
。也就是说,它们都是对const
string
的引用,所以在这种情况下,它没有区别。
有些人喜欢把它放在左边(比如const int
),因为它是从左到右读的。有些人喜欢把它放在右边(比如int const
),以避免使用特殊情况(例如,int const * const
比const int* const
更一致)。
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.
在这种情况下,无论哪种方式,它都可以工作,并且是个人偏好和编码约定的问题。
一些程序员更喜欢把它放在类型名称之后,这样它与const
的其他用法更一致。例如,如果要声明指针本身(而不是指向的类型)const
,则需要将其放在星号之后:
string * const ptr;
类似地,如果要声明一个const
成员函数,它需要在函数声明之后;例如:
class Foo
{
void func() const;
};
相关文章:
- 在 OpenCV 的 namedWindow 之前或之后初始化 Tesseract
- 在 C++20 之前,在带有常量或引用字段的"A"上调用 'std::vector<A>
- 如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
- 减去常量或将常量添加到大数组中
- 除以常量或变量零
- #pragma 一次位置:在 #include 之前或之后
- 快速报告 - 在显示准备报告之前或之后清除最后报告
- C++:如何创建一个临时对象,包含一个指针 - 常量或非常量,具体取决于上下文
- Winsockets - 身体之前和/或之后的奇怪字符
- 是在C 静态初始化之前或之后调用dllgetClassObject
- 为什么常量(或空头)在lambdas中被隐式捕获
- 字符常量或字符串常量
- 是在默认构造函数之前或之后调用的初始化列表
- 在C++中,作为类成员的引用应为常量或非常量
- EOF 位:读取失败之前或之后
- 类型之前或之后的常量
- 变量名应该在名词之前或之后有形容词吗
- ios_base::getloc应为常量或非常量
- 为什么我必须声明这些引用参数常量或按值传递
- 在方法名称之前或之后放置常量、静态和虚拟