我尝试调用我的重载插件,但它没有做它应该做的事情。
#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&lt;&lt; 5或任何数字都不会调用重载的插入运算符。我希望它具有与sll-&gt;(5)相同的功能。因此,不是使用sll->(x),而是将要完成的所有事情都是cout&lt;&lt; X;
答案 0 :(得分:0)
我不确定你想要实现的目标,但
cout&lt;&lt; 5
调用cout标准流的插入运算符。如果你想调用自己的插入操作符,至少左边的部分语句必须是你的类。 我希望这有帮助。