i've been stuck for days now so... i'm trying to compare two objects, one is p of type plane, the other is a plane stored in l[i] of type list. i need to overload the operator< to compare the two types using strcmp so i have:
i can't seem to figure out how i can access list l at position [i] to compare it to the other plane. do i need a friend function? thanks.
bool operator< (const plane& p) const
//postcondition: returns true if the implicit argument
//is less than the explicit argument using a key of
//model name, tail number order
const char* pModel = p.getModel();
const char* pNum = p.getNumber();
if (strcmp(pModel, ????) < 0
&& strcmp(pNum, ????) < 0)
So, first of all, you should certainly supply the model and number from your current object to strcmp().
The next thing is that your condition is a bit broken. If two planes are of equal model, then you shouldn't return false, should you? At that point, it should come down to the number.
So your condition should be:
cmp = strcmp(pModel, model);
// If it's "less" then we should return true.
if (cmp < 0)
// if it's equal, we defer to the number:
if (cmp == 0 && strcmp(pNum, ????) < 0)
// All other cases end up here, and of course are false.
thanks that helped with the logic, but just to get it to compile i need to know how to access l[i]'s atrributes from the overloaded operator code. the overload is in a plane.cpp. the list.cpp is where the comparing will be done.
so really i want something like this in the list.cpp:
void list::insert(const plane& p)
i = 0;
if (size >= MAX_LIST)
throw listException("List is full");
while (i <= size && list[i] < p)
i++; //...this isn't really done being code...
plane p2 = list[i];
then compare the p with the p2. i guess i'm having scope issues as well.
otherVar = p2.getModel();
For one, you have to make operator< be either a member function of plane, or take two parameters. The latter is preferred if you don't have to access private or protected data, or if the plane object allows implicit conversion.
As far as I can tell, if the list consists of an array of plane, then you should be able to use the plane::operator<() function as defined above. The compiler will automatically understand what's going on.
If your list holds some generic list item, and the plane is derived from the generic list item, as long as the operator<() is defined as a virtual function for the base class, it should work out just fine for the list insertion.