简体   繁体   中英

How to overload the [] operator to support both assignment and const parameters in other functions?

Consider a class SomeClass :

class SomeClass{
    public:
        // Constructors, other members
        float& operator[](const unsigned i);
        friend bool operator==(const SomeClass &A, const SomeClass &B);
};

Suppose this is how the == operator is overloaded for this class (not the actual implementation, but an overly simplified version):

bool operator==(const SomeClass &A, const SomeClass &B){
    if (A[0] == B[0])
        return true;
    return false;
}

This would throw a compiler error, since the overloaded [] operator requires the instance to be non- const . However, if I change the definition of the [] operator to allow for const instances, I can no longer do assignment:

// ASSUMING: const float& operator[](const unsigned i) const;

SomeClass a;
a[0] = 0; // error, because the return value of [] is a reference to const!

I really don't want to drop the const in the parameters of the == operator, since the operands don't change within the function. What is the right way to deal with this issue?

Overload operator [] to provide both:

float& operator [](unsigned int i);
float operator [](unsigned int i) const;

For a generic T that's not cheap to copy, use a T const& return value. The general pattern for implementing read/write operator [] is

T& operator [](index_type i);
T const& operator [](index_type i) const;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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