Operator Overload Problem

I'm trying to come up with the union of two Vector ADT bags, so I have to overload the '+' operator, but I'm getting a bunch of error messages saying:

1
2
3
4
5
VectorBag.cpp: In instantiation of ‘VectorBag<ItemType> VectorBag<ItemType>::operator+(VectorBag<ItemType>) [with ItemType = int]’:
proj2.cpp:161:42:   required from here
VectorBag.cpp:81:24: error: no match foroperator[]’ (operand types are ‘VectorBag<int>’ and ‘int’)
   newBag.add(anotherBag[i]);
                        ^


Here is the function to overload the operator:

1
2
3
4
5
6
7
template<class ItemType>
VectorBag<ItemType>
VectorBag<ItemType>::operator+(VectorBag<ItemType> anotherBag) {
    VectorBag<ItemType> newBag;
    for (int i = 0; i < anotherBag.getCurrentSize(); i++)
        newBag.add(anotherBag[i]);
}


the add() function is pre-defined by me somewhere else in the code. It basically does push_back().

Any ideas on what my problem could be?
Last edited on
Does VectorBag have an operator[]?
closed account (2AoiNwbp)
It seems you must overload operator[], at least that is what it states in line 3 of the output.
No, VectorBag does not have operator[]. But how would I overload for that?
Similar to any other operator:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template <typename T>
class VectorBag {
    public:
        // ...

        T& operator[](std::size_t pos) {
            // example implementation - you could throw some range 
            // checking in too, if you wanted
            return _data[pos];
        }

        // overload for constant VectorBags
        const T& operator[](std::size_t pos) const {
            return _data[pos];
        }

    private:
        T* _data;
        // ...
};
Last edited on
Topic archived. No new replies allowed.