overloading assignment operator With subscript operator

后端 未结 5 421
忘了有多久
忘了有多久 2020-12-19 16:31

I overloaded both subscript operator and assignment operator and I am trying to get right value to assignment operator example Array x; x[0]=5; by overloading

5条回答
  •  时光说笑
    2020-12-19 17:06

    If you remove the overloading of the = operator in your code, then you'll already have the behaviour you're desiring, since your overloaded [] operator returns a reference to the list item. For example:

    #include 
    using namespace std;
    
    template
    class Array {
        private:
            // This method is used to reallocate our array when the number of elements becomes equal to the length of the array.
            void _grow() {
                length *= 2;
                T* temp = new T[length];
                // Copy over the array elements
                for (int i = 0; i <= current; i++) {
                    temp[i] = items[i];
                }
                // Delete the old array
                delete [] items;
                // Set the array pointer equal to the pointer to our new memory, then annihilate the temp pointer
                items = temp;
                temp = NULL;
            }
    
        public:
            unsigned int length, current;
            T* items;
    
            // Constructor and destructor
            Array() {
                current = 0;
                length = 128;
                items = new T[length];
            }
            ~Array() {
                delete [] items;
                items = NULL;
            }
    
            // Overload the [] operator so we can access array elements using the syntax L[i], as in Python
            T& operator[] (unsigned int i) {
                return items[i];
            }
    
            // Add items to the Array if there is room.  If there is no room, grow the array and then add it. 
            void push(T b) {
                if (current + 1 < length) {
                    items[current] = b;
                    current += 1;
                } else {
                    _grow();
                    items[current] = b;
                    current += 1;
                }
            }
    };
    int main() {
        Array L;
        L[0] = 10;
        L[1] = 15;
        std::cout << L[0] << endl;
        std::cout << L[1] << endl;
        return 0;
    }
    

    Output:

    jmracek:include jmracek$ g++ Array.cpp -o a
    jmracek:include jmracek$ ./a
    10
    15
    

    If I were being careful, I would also include error handling for the case where I try and $L[i]$ and element outside of the array length.

提交回复
热议问题