C++: Overloading the [ ] operator for read and wri

2019-01-19 22:38发布

In general, how do you declare the index [ ] operator of a class for both read and write accesss?

I tried something like

/**
 * Read index operator.
 */
T& operator[](T u);

/**
 * Write index operator
 */
const T& operator[](T u);

which gives me the error

../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)'

3条回答
Viruses.
2楼-- · 2019-01-19 22:54

You simply have one overload that'll be used for both reads and writes:

T& operator[](int);

Having said that, you might also want to have a const overload:

const T& operator[](int) const;

This will provide read-only indexing into const instances of your class.

查看更多
戒情不戒烟
3楼-- · 2019-01-19 23:05

Your mutable version is fine:

T& operator[](T u);

but the const version should be a const member function as well as returning a const reference:

const T& operator[](T u) const;
                         ^^^^^

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.

查看更多
混吃等死
4楼-- · 2019-01-19 23:05

You get the error, because overloaded functions cannot differ only by return type. But they can differ by const-ness.

/**
 * Write index operator.
 */
T& operator[](T u);

/**
 * Read index operator
 */
const T& operator[](T u) const;

Note "write" and "read" swapped places.

Also, don't you actually mean the argument of the operator to be some integral type ?

查看更多
登录 后发表回答