c++ - 为什么在重载下标运算符时使用 const int 参数?

标签 c++ operator-overloading constants

我是 C++ 的新手所以你能解释一下我为什么/什么时候应该使用它吗

int & MyArray::operator[] (const int i)
{
    return arr[i];
}

而不是这个

int & MyArray::operator[] (int i)
{
    return arr[i];
}

最佳答案

这并没有太大的不同!

有些人喜欢将参数视为不可变的,因此他们将它们标记为const。在这种情况下,这是一种风格。

关于c++ - 为什么在重载下标运算符时使用 const int 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21042437/

相关文章:

c++ - 在某个类的析构函数中删除指向对象的指针会自动从堆中删除吗?

C++ << 运算符重载

c++ - 对 double 的二维 vector 进行排序

c# - C++ 运算符重载

java - 常量接口(interface)最优雅的替代方案是什么?

c++ - 在不使用空格的情况下输入两个数据或输入

c++ - ostream 运算符重载

c++ - operator<< 用于嵌套类

c++ - 错误 : qualifiers dropped in binding reference of type string to initializer of type const string

c++ - 如果变量名不跟在 char* 后面,const char* 是否有效?