1

I have an assignment about operator overloads. I did 11/13 of them, but I'm stuck on the last 2 (which are similar). I have a linked list class, and I've been assigned to overload list1+(int i), which I've already done. I also need to overload i+list1, and this is where I'm having difficulties, because I also have a cout<< overload. Examples I've found in stackoverflow caused problems with this cout operator (I'm not sure why.)

SortedDoublyLinkedList SortedDoublyLinkedList::operator+(int i)
{
    SortedDoublyLinkedList newlist(*this);
    newlist.add(i);
    return newlist;

}

This is the piece for list+integer, but I couldn't handle the reverse case, as I described.

neminem
  • 2,658
  • 5
  • 27
  • 36
enesdisli
  • 23
  • 6

2 Answers2

2

As a non-member function (it may have to be a friend).

 SortedDoublyLinkedList operator+(int i, const SortedDoublyLinkedList& list) 
   {...}

You'll probably also want to rewrite your existing one as:

 SortedDoublyLinkedList operator+(const SortedDoublyLinkedList& list, int i) 
   { ... }

You'll also probably want to have one call the other, or, better, have both call a SortedDoublyLinkedList::Add() method.

James Curran
  • 101,701
  • 37
  • 181
  • 258
1

to implement i+list1 you must define a friend non member operator like

class SortedDoublyLinkedList {
...

friend SortedDoublyLinkedList operator+(int i, const SortedDoublyLinkedList &_list);
};

SortedDoublyLinkedList operator+(int i, const SortedDoublyLinkedList &_list) {
    SortedDoublyLinkedList newlist(_list);
    newlist.add(i);
    return newlist;
}
Massimo Costa
  • 1,864
  • 15
  • 23