【问题标题】:Help to call overloaded insertion operator帮助调用重载的插入运算符
【发布时间】:2011-04-28 06:39:39
【问题描述】:

我尝试调用我的重载插入器,但它没有做它应该做的事情。

#include <iostream>
#include "SortedLinkedListInt.h"
#include <sstream>
using namespace std;

//CONSTRUCTOR
SortedLinkedListInt::SortedLinkedListInt(){
    head = NULL;
    size = 0;   
}

//DESTRUCTOR
SortedLinkedListInt::~SortedLinkedListInt(){    
    while (head != NULL) {
        Node* ptr = head;
        head = head -> next;
        delete ptr;     
    }

}
//COPY CONSTRUCTOR
SortedLinkedListInt::SortedLinkedListInt(const SortedLinkedListInt &obj){
    for(Node* n = obj.head; n!=NULL; n=n->next)
        add(n->data);
}

void SortedLinkedListInt::add(int newElement){  
    if (head == NULL){
        head = new Node;
        head->next = NULL;
        head->data = (newElement);
    }
    else if(head->data > newElement){
        Node* node1 = new Node;
        node1->data = newElement;
        node1->next = head;
        head = node1;
    }
    else{
        Node* node2;
        for(node2=head; node2->next!= NULL; node2 = node2->next)
            if(node2->next->data > newElement)
                break;

        Node* node = new Node;  
        node->next = (node2->next);
        node->data = (newElement);
        node2->next = (node);
        ++size;
    }

}

bool SortedLinkedListInt::exists (int element){
    for (Node* n = head; n != NULL; n = n -> next) // how to write n.getElement() in c++
        if(element == n->data) //analogous to compareTo (java)
            return true;
    return false;
}

void SortedLinkedListInt::toString(){
    for (Node* n = head; n != NULL; n = n->next){
        cout << n->data << endl;
    }
    cout << "\n";

}

void SortedLinkedListInt::operator <<(const int &sub){
    add(sub);
    for (Node* n = head; n != NULL; n = n->next){
        cout << n->data << endl;
    }
    cout << "\n";
}

函数在上述头文件的底部。下面是main.cpp

#include <iostream>
#include "SortedLinkedListInt.h"
#include <cstdio>
using namespace std;


int main(){

    SortedLinkedListInt *sll = new SortedLinkedListInt();
    //SortedLinkedList <int> *sll = new SortedLinkedList<int>;
    /*SortedLinkedList<int> sll2 = *sll;*/


    sll->add(5);
    sll->add(1);
    sll->add(3);
    sll->add(9);
    sll->add(2);
    sll->add(5);

    cout << 5;
    cout << 3;

    //sll->toString();

    int n = 4;

    printf("%d does%s exist in list.\n", n, sll->exists(n) ? "": " not");


    system("PAUSE");

}

cout (5) 相同的功能。所以不是使用 sll->(x) 而是 cout

【问题讨论】:

    标签: operator-overloading


    【解决方案1】:

    我不确定你想要达到什么目的,但是

    cout

    调用cout标准流的插入操作符。如果要调用自己的插入运算符,则语句的至少左侧部分必须是您的类。 我希望这有帮助。

    【讨论】:

      猜你喜欢
      • 2011-10-11
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多