链表中的重载运算符<<

Overloading operator << in linked list

本文关键字:lt 运算符 重载 链表      更新时间:2023-10-16

我目前正在大学学习,我正在努力完成我目前的项目。任务是创建一个链表,该链表将存储大于整数的数字,并添加将执行一些简单操作的函数,如<<,>>,+,-.虽然我已经解决了整个链表,但我正在努力思考如何重载运算符<<和>>。我尝试了几件事,用谷歌搜索了一下,但没有解决方案可以真正解决我的问题。一般的想法是将一个数字作为字符串,然后将其分成许多 1 位数字并将其放入我的列表中,但没有工作<<我什至无法开始。 我的清单.h

#ifndef LISTA_H_INCLUDED
#define LISTA_H_INCLUDED
#include <iostream>
using namespace std;
struct List {
private:
struct Node {
int data;
Node *next;
Node(int _data, Node *_next = NULL) {
data = _data;
next = _next;
}
};
Node *head, *tail;
int counter;
public:
List();
~List();
friend ostream& operator<<(ostream& wyjscie,const List& L);
//friend ostream& operator>>(ostream& wejscie,const List& L);
//customowe funkcje
};
#endif // LISTA_H_INCLUDED

和列表.cpp

#include "lista.h"
List::List()
{
head = NULL;
tail = NULL;
counter = 0;
}
List::~List()
{
while(head != NULL)
{
Node *killer = head;
head = head -> next;
delete killer;
}
tail = NULL;
counter = 0;
}
ostream& operator<<(ostream& wyjscie,const List& L)
{
Node *temp;
for(temp = L.head; temp != 0; temp = temp -> next)
{
wyjscie << temp -> data;
wyjscie<<endl;
}
return wyjscie;
}

问题是 Node 没有在这个范围内声明,当我尝试在没有这个临时节点的情况下这样做时,我也失败了,因为列表是常量。 提前感谢您的任何提示。

编辑

第一个问题解决了。我转移到重载运算符>>。我创建并插入(字符串 a( 函数,该函数获取字符串,将其除以并插入到链表中。这样做之后,我认为重载运算符>>将只使用该函数。我不确定为什么它不起作用。

void List::insert(string a)
{
int n=a.size();
for(int i=0;i<n;++i)
{
Node *nowy=new Node(a[i]);
if(head==nullptr)
{
head=nowy;
tail=nowy;
}
else
{
(*tail).next=nowy;
tail=nowy;
}
}
}
istream& operator>>(istream& wejscie,const List& L)
{
wejscie >> List::insert(string a);
return wejscie;
}

我也尝试了这样的事情:

istream& operator>>(istream& wejscie,const List& L)
{
string a;
cin >>a;
wejscie >> L.insert(a);
return wejscie;
}

我的主要职能

#include "lista.h"
int main()
{
List T1;
List T2;
T1.insert("54321");
cout << T1 << endl;
cin >> T2;
cout << T2;
}

函数

ostream& operator<<(ostream& wyjscie,const List& L)

未链接到List类,因此应指定List在其中使用Node

换句话说,您应该使用List::Node *temp;而不是Node *temp;.

对于编辑部分

为什么你的程序不起作用:

istream& operator>>(istream& wejscie,const List& L)
{
// List::insert isn't telling which list to insert
// "string a" here is invalid syntax
wejscie >> List::insert(string a);
return wejscie;
}
// L is const, so insertion won't be accepted
istream& operator>>(istream& wejscie,const List& L)
{
string a;
// cin suddenly appeared from somewhere
cin >>a;
// return type of L.insert(a) is void, so it won't suit for operand of >> operator
wejscie >> L.insert(a);
return wejscie;
}

(我的猜测(你应该做的是:

  1. wejscie读取字符串
  2. 将其"插入"到L

它的实现:

istream& operator>>(istream& wejscie,List& L)
{
string a;
wejscie >> a;
L.insert(a);
return wejscie;
}