user1822789
user1822789

Reputation: 45

C++ operator+ overload singly linkedlist

I'm trying to write an operator overload for a linked list which will take the right hand side of the + and concatenate that linked list to the list on the left hand side.

Class declaration:

 List<T>& operator+(const List<T>& right);

Method:

template <typename T>
List<T>& List<T>::operator+(const List<T>& right){
    List result(*this);
    while(right->next != NULL){
         result->push_back(right->data);
    }
    return list;
}

Driver:

mylist + mylist2; //both list objects already created.

Error message:

 Error: The operation "List<std::string>* + List<std::string>*" is illegal.

I'm unsure of why I get the compile time error. My logic is to take each element of the list on the right hand side and simply push it to the back of the list on the left hand side. Thoughts?

Upvotes: 0

Views: 2170

Answers (1)

juanchopanza
juanchopanza

Reputation: 227418

The exact error you are reporting is probably in code you have not shown, but it is important to point out that operator+ should not return a reference. You need a member operator

List<T> operator+(const List<T>& right);

or a non-member version,

template <typename T>
List<T> operator+(const List<T>& lhs, const List<T>& rhs);

You can implement either in terms of a member += operator, where you append the elements of lhs to *this and return *this by reference. The logic in your example is flawed, I leave it up to you to fix that, but this is the general form:

List<T>& operator+=(const List<T>& rhs)
{
  // append elements from rhs into *this
  ....
  return *this;
}

Your operator+ implementation then becomes quite simple:

template <typename T>
List<T> operator+(const List<T>& lhs, const List<T>& rhs)
{
  List<T> tmp = lhs;
  tmp += rhs;
  return tmp;
}

Upvotes: 1

Related Questions