本文介绍了为什么std :: basic_string :: operator []是一个const方法,如果它也是一个非const方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! http://cplusplus.com/reference/string/basic_string/operator [] 我理解,有一个第二个版本返回 const code> const result是为了减少转换,但是如果函数已经提供了一个非 const 方法)然后声明 const -result方法 const ? const )版本不仅会返回 >一个不同的结果,但也被标记为 const (这是声明结束时的第二个 const : const_reference运算符[](size_type pos)const; 这两个不同的东西: const 在非 - const 方法的情况下不需要返回值本身(因为非const返回值总是可以被转换为 const version)。 但是没有操作符的 const 意味着您不能在 const 字符串对象上使用它。 const 结果只是运算符本身的 const 结果:如果你有一个 const string并使用运算符获得对单个字符的引用,显然这个引用也必须是 const (如果没有,你可以更改 const string)。 http://cplusplus.com/reference/string/basic_string/operator[]I understand that it's advantageous to have a second version which returns const to prevent warnings when a const result is required and to mitigate casting but if the function already provides a non-const method (method-- not result) then what is the point of declaring the const-result method const? 解决方案 You need to understand, that the second (const) version not only returns a different result but is also marked itself as const (this is the second const at the end of the declaration):const_reference operator[] (size_type pos) const;These are two different things: The const return value by itself would not be needed in the presence of a non-const method (since the non-const return value can always be casted tò the const version).But not having a const-version of the operator would mean, that you couldn't use it on const string objects.The const result is just a result of the constness of the operator itself: if you have a const string and use the operator to get a reference to a single character, clearly this reference must also be const (if not, you could change single characters within a const string). 这篇关于为什么std :: basic_string :: operator []是一个const方法,如果它也是一个非const方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-21 18:59