ecatalano
ecatalano

Reputation: 687

Invalid operands with overloaded operator <<

I am trying to use a << operator to call an insert method on a linkedlist, such as:

a<<b
takes data b and inserts it into LinkedList a

Here is my implementation in my .h and .cpp files:

class LinkedList{
public:
    LinkedList();
    LinkedList(const LinkedList &l); //copy constructor
    ~LinkedList(); //destructor

    //read the list for items
    bool reset();
    bool next();
    int get();
    //insert an item in the list
    bool insert();
    bool insert(int &data);

    //delete an item in the list
    bool remove();

    //Should take data b and add it to the linked list a
    void operator<< (int data);
;
    //advances the internal iterator 1 node if not null
    void operator++ ();

_________________________________________
Linkedlist.cpp

void LinkedList::operator<<(int &data)
{
    insert(data);
}
bool LinkedList::insert(int &data){
    LinkedListNode* n;
    LinkedListNode *tempNode;
    n = new LinkedListNode();
    n -> data = data;
    if(head==NULL){
        head = n;
        current = head;
        size++;
        return true;
    }
    if(head->next!=NULL){
        tempNode = head->next;
    }
    else{
        tempNode = head;
    }
    while(tempNode->next!=NULL){
        tempNode = tempNode->next;
    }   
    head->next = n;
    size++;
    return true;
    }

in my main, I use:

l<<num;

and get the error:

invalid operands to binary expression ('LinkedList *' and
  'int')

Why is this happening if I overloaded the operator in my LinkedList class?

Upvotes: 1

Views: 163

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

Because l is a LinkedList *, and not a LinkedList. By overriding << on a LinkedList, you do not get an automatic override on LinkedList *, too.

Upvotes: 6

Related Questions