Search code examples
c++operator-overloadingdynamic-arraysbrackets

How to overload and use two different operators simultaneously in C++?


I want to redefine the two operators bracket "[]" and equal "=" in C++ language and use them simultaneously. In fact, I want to create a dynamic array and use it like usual arrays in C++ language. For example, do the assignment like normal arrays. For example:

MyDynamicArray myarray;
myarray[0] = 1;
myarray[1] = 7;
myarray[2] = 3;

What is important to me is the redefining of the assignment and bracket operators and their simultaneous use within my code.

My dynamicarray.h file is:

#include <iostream>

template<typename anyType>
class DynamicArray {
    private:
        Linear_Singly_Linked_List<anyType> *D_Arr;
        bool assignmentflag;
    public:
        DynamicArray() {
            D_Arr = new Linear_Singly_Linked_List<anyType>;
            assignmentflag = false;
        }
        unsigned int GetNumberOfNodes() {
            return D_Arr->get_number_of_nodes();
        }
        void Store(unsigned int index, anyType object);
        anyType operator = (anyType object) {
            if (assignmentflag) 
                D_Arr->append(object);
        }
        anyType operator [] (unsigned int index) {
            return D_Arr->display_of_data_node(index + 1);
            assignmentflag = true;
        }
};

template<class anyType> void DynamicArray<anyType>::Store(unsigned int index, anyType object) {
    if (D_Arr->get_number_of_nodes() == index) {
        D_Arr->append(object);
    }
    else if (index >= 0 && index < D_Arr->get_number_of_nodes()) {
        D_Arr->replacement(index+1,object);
    }
    else if (index > D_Arr->get_number_of_nodes()) {
        for (unsigned int i = D_Arr->get_number_of_nodes() ; i < index ; i++) {
            anyType nul = NULL;
            D_Arr->append(/*NULL*/nul);
        }
        D_Arr->append(object);
    }
}

and my dynamicarrayTester.cpp file is:

#include <iostream>
#include "dynamicarray.h"

using namespace std;

int main() {
    DynamicArray<int> a;

    a[0] = 27;

    a.Store(0,-7);
    a.Store(1,-5);
    a.Store(2,3);
    a.Store(3,2);

    a[3] = 7;

    cout << a[0] << endl;
    cout << a[1] << endl;
    cout << a[2] << endl;
    cout << a[3] << endl;
}

In the part where a[0] = 27; I get "expression must be a modifiable lvalue" error.


Solution

  • You need to overload operator[] to return a reference. E.g.

    #include <iostream>
    
    template <typename T>
    class Arr {
        T *data;
        std::size_t size;
    
    public:
        Arr(std::size_t size) : data(new T[size]), size(size) { }
    
        ~Arr() { delete [] data; }
    
        T & operator[](std::size_t i) {
            return data[i];
        }
    };
    
    int main() {
        Arr<int> arr{10};
    
        arr[3] = 42;
    
        std::cout << arr[3] << std::endl;
    }