Couple of comments:
- copy constructor would normally have its ref argument const. Also your constructor code is very inefficient using insertAfter() and next(). Also, as first(), next() etc alters pos, the argument can't be const. Consider:
1 2 3 4 5 6 7 8
|
List::List(const List& l)
{
sz = l.sz;
pos = l.pos; // May want 0??
for (int i = 0; i < CAPACITY; ++i)
ary[i] = l.ary[i];
}
|
- setPos() can be simplified. Consider:
1 2 3 4 5 6 7
|
void List::setPos(int i)
{
if (sz == 0 || i < 0)
pos = 0;
else
pos = (sz > 0 && i > sz - 1) ? sz - 1 : i;
}
|
- inc() should test for end of list
1 2 3 4 5
|
void List::inc()
{
if (sz < CAPACITY)
++sz;
}
|
- the insertBefore()/insertAfter() functions can simplified:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
// insertBefore inserts a new element before the current position
void List::insertBefore(ElementType val)
{
if (sz == 0)
pos = 0;
else
if (sz < CAPACITY)
for (int i = sz; i > pos - 1; i--)
ary[i] = ary[i - 1];
ary[pos] = val;
++sz;
}
// insertAfter inserts a new element after the current position
void List::insertAfter(ElementType val)
{
if (sz == 0)
pos = 0;
else
if (sz < CAPACITY)
{
for (int i = sz; i > pos; i--)
ary[i] = ary[i - 1];
pos++;
}
ary[pos] = val;
++sz;
}
|
- why does clear() use pointers?
1 2 3 4 5 6 7 8
|
void List::clear()
{
for (int i = 0; i < CAPACITY; ++i)
ary[i] = 0;
sz = 0;
pos = -1;
}
|
- empty - as per previous comment can be simplified:
1 2 3 4 5
|
// empty returns true or false if list is empty or not.
bool List::empty() const
{
return sz == 0;
}
|
- operator==(), if the sizes of the two lists aren't equal then the result is false without any further tests. The same for operator!=
1 2 3 4 5 6 7 8 9 10 11 12 13
|
bool List::operator==(List& l) const
{
if (l.sz != sz)
return false;
l.first();
for (int i = 0; i < sz; ++i, l.next())
if (ary[i] != l.getElement())
return false;
return true;
}
|
-also for operator!=, this is the inverse of operator==, so is simply:
1 2 3 4
|
bool List::operator!=(List& l) const
{
return !operator==(l);
}
|
- I'm not sure that the operator+() is correct. In the original post the declaration is
List operator + (List& ListA, List& ListB);
which is what I would be expecting (except the args should be const). operator() wouldn't expect to change the contents of the current list, but create a new list with the specified argument list appended to the current list and returned.
- operator=() this is the same as copy constructor - re same comment