const 关键字在运算符定义中的作用是什么?
What does the const keyword do in an operator definition?
不明白这个运算符定义的return类型前面和参数列表后面的const关键字是干什么用的。这是取自一本书的例子。
const char& operator [] (int num) const
{
if (num < getlength())
return Buffer[num];
}
C++ const
关键字的基本意思是 "something cannot change, or cannot delegate operations that change onto other entities." 这指的是一个特定的变量:要么是任意的变量声明,要么是在成员函数中隐式地指向 this
。
const
之前函数名是return类型的一部分:
const char&
这是对 const char
的引用,这意味着无法为其分配新值:
foo[2] = 'q'; // error
函数定义最后的const
表示"this function cannot change this
object and cannot call non-const functions on any object.",也就是说调用这个函数不能改变任何状态。
const char& operator [] (int num) const {
this->modifySomething(); // error
Buffer.modifySomething(); // error
return Buffer[num];
}
const
-正确性的目标是一个很大的话题,但简短的版本是能够保证不可变状态实际上是不可变的。这有助于线程安全并帮助编译器优化您的代码。
这意味着您调用此方法的实际对象不会更改,如果您尝试更改它,则会出现编译器错误。
不明白这个运算符定义的return类型前面和参数列表后面的const关键字是干什么用的。这是取自一本书的例子。
const char& operator [] (int num) const
{
if (num < getlength())
return Buffer[num];
}
C++ const
关键字的基本意思是 "something cannot change, or cannot delegate operations that change onto other entities." 这指的是一个特定的变量:要么是任意的变量声明,要么是在成员函数中隐式地指向 this
。
const
之前函数名是return类型的一部分:
const char&
这是对 const char
的引用,这意味着无法为其分配新值:
foo[2] = 'q'; // error
函数定义最后的const
表示"this function cannot change this
object and cannot call non-const functions on any object.",也就是说调用这个函数不能改变任何状态。
const char& operator [] (int num) const {
this->modifySomething(); // error
Buffer.modifySomething(); // error
return Buffer[num];
}
const
-正确性的目标是一个很大的话题,但简短的版本是能够保证不可变状态实际上是不可变的。这有助于线程安全并帮助编译器优化您的代码。
这意味着您调用此方法的实际对象不会更改,如果您尝试更改它,则会出现编译器错误。