Hi, I have a Basket class, containing Apple objects, stored in an Basket.
A Apple object is described by coordinates x, y.
I'm trying to override the [] operator, but it's not working:
Basket2[0] = Apple1; // Not working: no operator "=" matches this operand, operand types are Basket = Apple
class Basket
{
private:
Apple* m_data;
int m_size;
public:
Basket(); //default Constructor
Basket(int size); //argument constructor
Basket(const Basket &Basket); //copy constructor
~Basket(); //destructor
Basket& operator = (const Basket& source); // Assignment operator
Apple& operator[](int index); //class indexer for writing
const Apple& operator[] (int index) const; //class indexer for reading
//Getter function
int Size() const; //returns size
//Get element by index
Apple& GetElement(int i);
void SetElement(constint index, const Apple& element); //set element of Basket to a new Apple
void Print(string msg);
};
//class indexer
Apple& Basket::operator [] (int index)
{
return (index > m_size - 1) ? m_data[0] : m_data[index];
}
const Apple& Basket::operator [] (int index) const
{
return (index > m_size - 1) ? m_data[0] : m_data[index];
}
int main()
{
//instantiate a Basket of two elements size
Basket* Basket1 = new Basket(2);
Apple Apple0(0, 0); //instantiate a Apple with coordinates x, y
Apple Apple1(1, 1);
Basket1->SetElement(0, Apple0); //set the first element of Basket1 to Apple0
Basket1->SetElement(1, Apple1);
Basket* Basket2 = new Basket(2);
Apple Apple2(2, 2); //instantiate a Apple with coordinates x, y
Apple Apple3(3, 3);
Basket2->SetElement(0, Apple2); //set the first element of Basket1 to Apple2
Basket2->SetElement(1, Apple3);
Basket2[0] = Apple1; // Not working: no operator "=" matches this operand, operand types are Basket = Apple
return 0;
}
The problem is that array1 and array2 are pointers, not Array objects.
You don't need to create your Array object itself with new, that's the beauty of RAII.