C ++:重载读取和写入访问的[]操作符 [英] C++: Overloading the [ ] operator for read and write access
本文介绍了C ++:重载读取和写入访问的[]操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一般来说,你如何为读和写访问声明一个类的索引 []
?
In general, how do you declare the index [ ]
operator of a class for both read and write accesss?
我尝试过
/**
* Read index operator.
*/
T& operator[](T u);
/**
* Write index operator
*/
const T& operator[](T u);
这给我错误
../src/Class.h:44:14: error: 'const T& Class::operator[](T)' cannot be overloaded
../src/Class.h:39:8: error: with 'T& Class::operator[](T)'
推荐答案
可变版本很好:
T& operator[](T u);
但是 const
code> const 成员函数以及返回 const
引用:
but the const
version should be a const
member function as well as returning a const
reference:
const T& operator[](T u) const;
^^^^^
这不仅区别于其他重载,允许(只读)访问您的类的 const
实例。一般来说,重载成员函数可以通过它们的参数类型和const / volatile限定条件来区分,但不是的返回类型。
This not only distinguishes it from the other overload, but also allows (read-only) access to const
instances of your class. In general, overloaded member functions can be distinguished by their parameter types and const/volatile qualifications, but not by their return types.
这篇关于C ++:重载读取和写入访问的[]操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文