I have an array class, containing Point objects, stored in an array. A point object is described by coordinates x, y. I'm trying to override the [] operator, but it's not working: array2[0] = point1; // Not working: no operator "=" matches this operand, operand types are Array = point
class Array
{
private:
Point* m_data;
int m_size;
public:
Array(); //default Constructor
Array(int size); //argument constructor
Array(const Array &array); //copy constructor
~Array(); //destructor
Array& operator = (const Array& source); // Assignment operator
Point& operator[](int index); //class indexer for writing
const Point& operator[] (int index) const; //class indexer for reading
//Getter function
int Size() const; //returns size
//Get element by index
Point& GetElement(int i);
void SetElement(const int index, const Point& element); //set element of array to a new point
void Print(string msg);
};
//class indexer
Point& Array::operator [] (int index)
{
return (index > m_size - 1) ? m_data[0] : m_data[index];
}
const Point& Array::operator [] (int index) const
{
return (index > m_size - 1) ? m_data[0] : m_data[index];
}
int main()
{
//instantiate an array of two elements size
Array* array1 = new Array(2);
Point point0(0, 0); //instantiate a point with coordinates x, y
Point point1(1, 1);
array1->SetElement(0, point0); //set the first element of array1 to point0
array1->SetElement(1, point1);
Array* array2 = new Array(2);
Point point2(2, 2); //instantiate a point with coordinates x, y
Point point3(3, 3);
array2->SetElement(0, point2); //set the first element of array1 to point2
array2->SetElement(1, point3);
array2[0] = point1; // Not working: no operator "=" matches this operand, operand types are Array = point
return 0;
}
Aucun commentaire:
Enregistrer un commentaire