具有重载运算符的无效操作数<<

时间:2016-03-08 13:22:27

标签: c++

我正在尝试使用<< operator在链表上调用insert方法,例如:

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

这是我在.h和.cpp文件中的实现:

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;
    }

在我的主要内容中,我使用:

l<<num;

并收到错误:

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

如果我在LinkedList类中重载了运算符,为什么会发生这种情况?

1 个答案:

答案 0 :(得分:6)

因为lLinkedList *,而不是LinkedList。通过覆盖<<上的LinkedList,您也无法在LinkedList *上获得自动覆盖。