jeudi 19 mars 2020

Overloading subscript operator in arrays by reference

I have a question about overloading subscript operators by reference, as shown in the following code:

#include <iostream>
#include <array>
using namespace std;

class NewArray
{
    public:
        typedef array<int, 1024> array_type;
        typedef int&             reference;
        reference operator[](const int i) {
            return array_[i];
        }
    private:
        array_type array_;
};

int main(){

    NewArray lhs, rhs;
    rhs[10] = 1000; // Assigning value to rhs[10]
    lhs[10] = rhs[10]; // Arrays references are the same
    rhs[10] = 0; // Modifying reference

    cout << lhs[10] << " " << rhs[10] << endl;

    return 0;
}

Given that I'm returning references to the array position, and the lhs[10] and rhs[10] references are equal, shouldn't the output be

0 0

instead of

1000 0

?

Aucun commentaire:

Enregistrer un commentaire