简体   繁体   English

const关键字在运算符定义中起什么作用?

[英]What does the const keyword do in an operator definition?

I don't understand what the const keyword is used for in front of the return type and after the parameter list of this operator definition. 我不明白const关键字在返回类型之前和此运算符定义的参数列表之后使用的含义。 This is taken from an example from a book. 这是从一本书的例子中得出的。

const char& operator [] (int num) const
{
    if (num < getlength())
        return Buffer[num];
}

The C++ const keyword basically means "something cannot change, or cannot delegate operations that change onto other entities." C ++ const关键字的基本含义是“某些内容无法更改,或者无法将更改后的操作委派给其他实体。” This refers to a specific variable: either an arbitrary variable declaration, or implicitly to this in a member function. 这是指特定的变量:任意变量声明,或在成员函数中隐式this声明。

The const before the function name is part of the return type: 函数名称const是返回类型的一部分:

const char&

This is a reference to a const char , meaning it is not possible to assign a new value to it: 这是对const char的引用,这意味着无法为其分配新值:

foo[2] = 'q'; // error

The const at the end of the function definition means "this function cannot change this object and cannot call non-const functions on any object." 函数定义末尾的const表示“此函数无法更改this对象,并且不能在任何对象上调用非const函数”。 In other words, invoking this function cannot change any state. 换句话说,调用此功能不能更改任何状态。

const char& operator [] (int num) const {
  this->modifySomething(); // error
  Buffer.modifySomething(); // error
  return Buffer[num];
}

The goal of const -correctness is a big topic, but the short version is being able to guarantee that immutable state actually is immutable. const -correctness的目标是一个大话题,但是简短的版本能够保证不可变状态实际上是不可变的。 This helps with thread safety and helps the compiler optimize your code. 这有助于提高线程安全性,并有助于编译器优化代码。

这意味着您正在调用此方法的实际对象不会更改,并且如果尝试更改它,则会出现编译器错误。

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

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