[英]Overloading operator << in linked list
我目前正在大学学习中,我正在努力完成我目前的项目。 任务是创建一个链接列表,该列表将存储大于整数的数字并添加将执行一些简单操作的函数,例如 <<、>>、+、-。 虽然我已经计算出整个链表,但我正在努力思考如何重载运算符 << 和 >>。 我尝试了几件事,用谷歌搜索,但没有解决方案真正解决我的问题。 一般想法是将一个数字作为字符串,然后将其分成许多 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
和 list.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 未在此范围内声明,当我尝试在没有此临时 Node 的情况下执行此操作时,我也失败了,因为 list 是 const。 提前感谢您的任何提示。
第一个问题解决了。 我转向重载运算符>>。 我创建了 insert(string a) 函数,它接受字符串,将其分割并插入到链表中。 这样做之后,我认为重载 operator>> 将只是使用该函数。 我不确定为什么它不起作用。
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;
}
(我的猜测)你应该做的是:
wejscie
读取一个字符串L
一个实现:
istream& operator>>(istream& wejscie,List& L)
{
string a;
wejscie >> a;
L.insert(a);
return wejscie;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.