What should the operator[] return in a function that returns the -n-th element in a list?
1 2 3 4 5 6 7 8 9 10 11 12
//This is the Class
class Customer {
private:
string name;
long number;
int bonus;
list<Product> recentOrders;
public:
/*Type*/operator[](long n) {
return recentOrders[n]; //Is this legal?
}
};
You return the type of the variable that is stored in the array. In your case, the return type should be a reference to Product. Remember that operator[] usually allows you to modify the element in the array (or pseudo-array).
Product& Customer::operator[](long n);
Line 10 is not legal because std::list does not overload operator[]. If you want to use operator[], you can always use std::vector. Else, you will have to create an iterator and "advance" it n places. Keep in mind that one of std::list's weaknesses is iterating to specific positions.
You should also remember to check if the index is less than 0 or is out-of-bounds.
Random Note:
You can also have a read-only version of operator[]: