[英]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.