简体   繁体   English

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

[英]Why use const int parameter when overloading the subscript operator?

I am new to C++ so can you please explain why/when should I use this 我是C ++的新手,所以请你解释为什么/什么时候我应该使用它

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

instead of this 而不是这个

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

It's doesn't make a huge amount of difference! 它并没有产生巨大的差异!

Some people like to treat parameters as immutable, so they flag them as const . 有些人喜欢将参数视为不可变参数,因此将它们标记为const In this case it's a stylistic thing. 在这种情况下,它是一种风格的东西。

In a function declaration , it makes absolutely no difference, because top-level const s are ignored. 在函数声明中 ,它完全没有区别,因为忽略了顶级const

These two are actually the same declaration, and for that reason, top level const in function parameters should be avoided: 这两个实际上是相同的声明,因此,应该避免函数参数中的顶级const

void foo(int);
void foo(const int); // re-declaration of above function

In a function definition , it means you cannot change the copy of the argument in your function: 在函数定义中 ,这意味着您无法更改函数中参数的副本:

void foo(int i) { i++; } // OK
void foo(const int i) { i++; } // Error

So, it can be used as an implementation artifact, to express that the local variable is const . 因此,它可以用作实现工件,以表示局部变量是const This gives the compiler more scope to perform optimizations. 这为编译器提供了更多执行优化的范围。

Don't do this. 不要这样做。 It's identical from caller's perspective and just adds visual noise. 它从呼叫者的角度来看是相同的,只是增加了视觉噪音。

The parameter i is passed by value and is a plain data type, it is copied, so when you mark it as const you are telling the compiler that it cannot change inside the method, but since it is a copy it isn't important at all, and in this specific example you are just using it as an index. 参数i按值传递并且是纯数据类型,它被复制,所以当你将它标记为const你告诉编译器它不能在方法内部改变,但由于它是一个副本,所以它并不重要所有,在这个具体的例子中,您只是将它用作索引。

Both forms are correct. 两种形式都是正确的。 Use the first one if you want to ensure that the "i" parameter will not be modified in the function, which may be useful if the function is longer/more complicated. 如果要确保在函数中不修改“i”参数,请使用第一个参数,如果函数更长/更复杂,这可能很有用。 However, in the declaration of the operator do not use const: 但是,在运算符的声明中不要使用const:

int& operator[](int i);

It is legal to have declaration without const, and definition with it. 没有const的声明和使用它的定义是合法的。

作为一种规则,任何你不打算修改的都应该是const

If you not trying to edit your parameter then its better to use const . 如果你不想编辑你的参数,那么最好使用const

As far as performance is concerned not much difference. 就性能而言,差别不大。 But it safeguards your parameter from editing ( accidentally ) inside function. 但它可以保护您的参数免于编辑( 意外 )内部功能。

int & MyArray::operator[] (const int i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM